javascript - 使用 "This"调用匿名函数时如何分配 "Call"?

标签 javascript oop call this

来自 MDN :

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);
    }
    this.print();
  }).call(animals[i], i);
}

在上面的例子中,“this”是如何在“animals”循环内的匿名函数中使用的?我很好奇为什么“this”指的是动物对象而不是窗口。

例如,如果我要从参数中删除 animals[i],那么一切都是未定义的。这是否意味着匿名函数从它们接收到的第一个参数中派生出它们的“身份”,或者是否还有其他事情发生?

提前致谢!

最佳答案

这不是在documentation of function.call()中解释的吗?你引用自己的话?

fun.call(thisArg[, arg1[, arg2[, ...]]])

Parameters

thisArg The value of this provided for the call to fun. [...]

及以后:

Description

You can assign a different this object when calling an existing function.

所以你是对的,animals[i] 在函数中用作 this。您可以将其视为始终具有 this 名称的隐式隐藏参数。

关于javascript - 使用 "This"调用匿名函数时如何分配 "Call"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13402951/

相关文章:

javascript - 使用pdf.js嵌入PDF到网页

android - 将音频文件播放到调用android中

javascript - Qt4:如何通过 QtWebkit 从 C++ 调用页面中的 JavaScript 函数?

c - linux系统c引用

javascript - 键盘导航 : how to go to the next and previous element with arrow keys?

javascript - ng-view 路由模板是否反射(reflect) ajax 请求导致的更改?

javascript - Greasemonkey 脚本在每个网站上运行

c++ - 通过成员数组循环给出错误的值

scala - 对象-功能阻抗不匹配

java - java枚举器中的私有(private)构造函数