我如何获得正确的"this"?在Array.map中? [英] How do I get the right "this" in an Array.map?
问题描述
我假设这里有call
或apply
的某些应用程序,但是我不确定如何实现它.
I assume there is some application of call
or apply
here but I'm not sure how to implement it.
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();
说我想map
一个数组,但是在函数中,我需要访问foo
所属的this
. map
的function
创建了一个新的this
上下文,因此我显然需要以某种方式强制返回该上下文,但是在仍然可以访问thing
的情况下该如何做呢?
Say I want to map
an array, but in the function, I need access to the this
to which foo
belongs. The function
of map
creates a new this
context, so I obviously need to coerse that context back in somehow, but how do I do that while still having access to thing
?
推荐答案
我意识到我应该更仔细地阅读Array.map()
的文档.只需将this
值作为map()
Just realized I should have read the documentation for Array.map()
more carefully. One simply needs to pass in the this
value as the second parameter of 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()
的工作方式.这些使我们可以跳过诸如此类的愚蠢任务
In addition, understanding how bind()
, call()
and apply()
work are a must for serious JavaScript developers. These allow us to skip silly assignments like
var self = this;
myItems.map(function(item) {
self.itemArray.push(item);
});
使用
myItems.map(function(item) {
this.itemArray.push(item);
}.bind(this));
这篇关于我如何获得正确的"this"?在Array.map中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!