gpt4 book ai didi

javascript - 使用箭头函数作为方法会意外产生 : MDN's example with []. Push.call()

转载 作者:行者123 更新时间:2023-12-01 02:57:27 25 4
gpt4 key购买 nike

无法重现 MDN's example (《以类似数组的方式使用对象》)使用基于箭头函数的方法。

> let obj = {
... length: 0,
... addEl: el => [].push.call(this, el={}) //default argument
... };

这很重要,但是……什么?它肯定将递增值存储在某个地方,但是在哪里呢?

> obj.addEl();
1
> obj.addEl({});
2
> obj
{ length: 0, addEl: [Function: addEl] } // array function «this» problem?

原始变体以正确的方式增加长度,但它也创建了新的属性。示例中没有任何内容。

addEl: function (el) { [].push.call(this, el) }
...
// the function in work
> anotherObj.addEl();
> anotherObj.addEl('new');
> anotherObj
{ '0': undefined,
'1': 'new',
length: 2,
addEl: [Function: addEl] }

还好吗?如果是这样,我想,它应该被称为“创建类数组对象”,不仅意味着长度属性,还意味着数字键。相关的,已回答的问题是 here .

最佳答案

递增值存储在window中,因为箭头函数不绑定(bind)this。它们的 this 值是封闭范围的值,在本例中是全局范围。例如:

let obj = {
length: 0,
addEl: el => [].push.call(this, el={}) //default argument
};

console.log(obj.addEl());
console.log(window.length);

window.length 是递增值。 obj.addEl() 返回递增值的原因是 Array#push 返回新的 length。如果您记录 window[0],您将获得推送到 this 的默认参数,即 window:

> window[0]
< {}

正则函数表达式行为不同的原因是它们绑定(bind)到对象 obj,因此 this 在正则函数中引用 obj与箭头函数中的 window 相反的表达式。

关于javascript - 使用箭头函数作为方法会意外产生 : MDN's example with []. Push.call(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635440/

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