【发布时间】:2012-11-04 08:57:38
【问题描述】:
来自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],那么一切都是未定义的。这是否意味着匿名函数从它们接收到的第一个参数中派生出它们的“身份”,还是发生了其他事情?
提前致谢!
【问题讨论】:
标签: javascript oop call this