来自 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 ofthis
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/