JavaScript中的这个call()-方法是如何工作的

how is this call()-method in javascript is working?

本文关键字:何工作 工作 方法 call JavaScript      更新时间:2023-09-26

我正在学习Javascript中的call((-method,并试图理解这个例子。现在我的问题是:

  • 为什么我在控制台(浏览器(中看不到任何内容;控制台.log((-方法;不是加工?
  • 这个匿名函数是如何工作的?

谢谢你的时间!

var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];
for (var i = 0; i < animals.length; i++) {
  (function (i) {
    this.print = function () {
      console.log('#' + i  + ' ' + this.species + ': ' + this.name);
    }
  }).call(animals[i], i); // I cant understand this anonymus func ? :(
}

尝试将此代码添加到示例的末尾:

animals[0].print();

匿名函数使用 call 调用,该函数用于在函数主体中设置this上下文。因此,当匿名函数使用this时,它实际上是在获取对从外部传入的当前动物的引用。

该函数使用 print 方法扩充this对象(即 currnet 动物(。仅此一项不会在控制台中显示任何内容。它仅表示print方法已添加到动物对象中。但是,您可以使用上面的代码访问对象的此方法。

展开循环,代码有效地执行以下操作:

animals[0].print = function () {
    console.log('#' + 0  + ' ' + this.species + ': ' + this.name);
}
animals[1].print = function () {
    console.log('#' + 1  + ' ' + this.species + ': ' + this.name);
}

理解这个例子的关键是要意识到,如果不使用 call,匿名函数中的 this 引用将自动引用全局window对象。它将使用 print 方法扩展window对象,这显然不是我们想要的。

下一步示例是通过向对象原型添加 print 方法来获得相同的结果。(这很可能是你书中的下一个例子(