关于构造函数在Javascrpt中的工作原理,我感到非常困惑.尽管使用该语言已有好几年了(大多数情况下它就像是LISP的半命令版本),但我想更多地了解对象应该如何工作.
鉴于此代码:
function Foo(x) {
return {
bar: function() { return x; }
};
}
Run Code Online (Sandbox Code Playgroud)
打电话myFoo = Foo(5)和有myFoo = new Foo(5)什么区别?或者,换句话说,Javascript中的构造函数究竟是做什么的?
我的代码库中有这一行:
var uncurryThis = Function.bind.bind(Function.call);
Run Code Online (Sandbox Code Playgroud)
我正在努力解决这个问题.据推测,它是不可靠的.我该如何解决这个问题?
我想这是一个版本Function.bind,其自身this必然Function.call.对我没有帮助.而且我没有找到任何用途,所以我甚至不确定你是单独称它还是需要"作为一种方法"来调用它,只是,你知道,首先绑定它.
有人可以解释这个功能吗?
var bindbind = Function.prototype.bind.bind(Function.prototype.bind);
Run Code Online (Sandbox Code Playgroud)
我理解它产生的结果:
var bindedContextFunc = bindbind(function)(context);
bindedContextFunc(args);
Run Code Online (Sandbox Code Playgroud)
但是不明白创建这个功能的过程,我的意思是部分 bind(Function.prototype.bind)
我真的可以使用任何人的解释.
对此代码严重困惑.尤其是第2行.
代码源是https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);
function list() {
return slice(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
Run Code Online (Sandbox Code Playgroud) 我读了一些文章,它说下面两行正在做同样的事情.
fn.call(thisValue);
Function.prototype.call.call(fn, thisValue);
Run Code Online (Sandbox Code Playgroud)
对于1号线,我的理解是,在Javascript中的每个函数对象也有方法call从继承的Function.prototype,哪些call不为法具有this的功能定义中的关键字fn是thisValue(我在调用方法传递的第一个参数.fn是函数所以我正在做的fn.call(thisValue)只是调用fn并设置this函数内的关键字thisValue.
但对于第2行,我不明白.有人可以帮助解释它是第2行正在做什么.