gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:08:52 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com