Javascript 为什么可以';t I var a=someFn.call;a();?
这似乎是矛盾的…在Chrome控制台中:Javascript 为什么可以';t I var a=someFn.call;a();?,javascript,prototype,call,typeerror,Javascript,Prototype,Call,Typeerror,这似乎是矛盾的…在Chrome控制台中: > var forEach = Array.prototype.forEach.call; > forEach function call() { [native code] } > Object.getPrototypeOf(forEach); function () {} > forEach([1,2,3], function(a) { console.log(a); }); Uncaught TypeErr
> var forEach = Array.prototype.forEach.call;
> forEach
function call() { [native code] }
> Object.getPrototypeOf(forEach);
function () {}
> forEach([1,2,3], function(a) { console.log(a); });
Uncaught TypeError: forEach is not a function
我猜在JS Internal function.call中,函数的处理方式与普通函数不同?在JavaScript中,函数是一等公民,就像字符串和int一样。执行此操作时,
Array.prototype.forEach.call
,您将获得.call
属性的值,该属性在prototype
链的上游是Function.prototype.call
。因此,您的forEach
变量设置为Function.prototype.call
现在,当您调用函数时,该函数中的this
的值取决于它的调用方式。当您执行forEach(…)
时,就像执行Function.prototype.call.call(null)
<代码>调用期望此
是一个函数,而它不是,因此它会抛出一个错误
您可能需要以下内容:
var forEach = Array.prototype.forEach;
forEach.call([1,2,3], function(a) { console.log(a); });
或者可能:
var forEach = Array.prototype.forEach.bind([1,2,3]);
forEach(function(a) { console.log(a); });
如果要执行forEach(array,fn) 现在,您可以像以前一样使用它:
forEach([1,2,3], function(a) { console.log(a); });
您正在做的是将调用this
绑定到Array.prototype.forEach
。这只是编写Array.prototype.forEach.call
的简写
如果将调用“调用”函数的方式可视化,则会更容易,因此想象调用函数会这样做(实际上不是这样):
现在假设bind
将绑定为this
的调用函数返回到Array.prototype.forEach.call
:
return Array.prototype.forEach.call(arg1, arg2, etc);
当然,你也可以自己做同样的事情:
var forEach = function(array, fn) {
return Array.prototype.forEach.call(array, fn);
}
虽然我不确定哪一个更好,但从性能角度来看。内部依赖于
此
的函数在与“所有者”分离时必须绑定以正常工作,因为对于未绑定的函数,此
值将是obj.func()中点左侧引用的对象。如果直接从当前作用域调用函数(例如func()
),则此
将指向窗口
因此,在下面的代码中,调用forEach
时,此
值将是窗口
,而您需要它是Array.prototype.forEach
var forEach = Array.prototype.forEach.call;
forEach([1, 2], function () {}); //this inside forEach is window
为了解决这个问题,我们可以将调用
绑定到Array.prototype.forEach
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
forEach([1, 2, 3], function (num) {
console.log(num);
});
由于这个
在JavaScript中的工作方式,someFunction.call
就是Function.prototype.call
。您可能需要设置this
值的.bind
-因此数组.prototype.forEach.call.bind(Array.prototype.forEach)
。正是这个错误让我大吃一惊:)这个错误更糟糕:数组.prototype.forEach()
未捕获类型错误:未定义不是函数(…)
var forEach = Array.prototype.forEach.call;
forEach([1, 2], function () {}); //this inside forEach is window
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
forEach([1, 2, 3], function (num) {
console.log(num);
});