Javascript 为什么可以';t I var a=someFn.call;a();?

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

这似乎是矛盾的…在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 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);
   });