gpt4 book ai didi

javascript - 如何在 Array.map 中获取正确的 "this"?

转载 作者:行者123 更新时间:2023-12-02 23:20:55 27 4
gpt4 key购买 nike

我假设这里有一些callapply的应用,但我不确定如何实现它。

http://codepen.io/anon/pen/oXmmzo

a = {
foo: 'bar',
things: [1, 2, 3],
showFooForEach: function() {
this.things.map(function(thing) {
console.log(this.foo, thing);
});
}
}

a.showFooForEach();

假设我想要映射一个数组,但在函数中,我需要访问foo所属的thismapfunction 创建了一个新的 this 上下文,因此我显然需要以某种方式将该上下文强制返回,但是我该如何做到这一点仍然可以访问事物

最佳答案

刚刚意识到我应该更仔细地阅读 Array.map() 的文档。只需将 this 值作为 map()

的第二个参数传递即可

http://codepen.io/anon/pen/VLggpX

a = {
foo: 'bar',
things: [1, 2, 3],
showFooForEach: function() {
this.things.map(function(thing) {
console.log(this.foo, thing);
}, this);
}
}
a.showFooForEach();

此外,对于认真的 JavaScript 开发人员来说,了解 bind()call()apply() 的工作原理是必须的。这些使我们能够跳过愚蠢的作业,例如

var self = this;
myItems.map(function(item) {
self.itemArray.push(item);
});

myItems.map(function(item) {
this.itemArray.push(item);
}.bind(this));

关于javascript - 如何在 Array.map 中获取正确的 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866390/

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