mtm*_*ald 14 javascript foreach this
将this上下文传递给匿名forEach函数的现代正确方法是什么?
function Chart() {
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(this); //question: how to get Chart instead of global scope?
)};
});
};
Run Code Online (Sandbox Code Playgroud)
the*_*eye 27
将电流存储this在其他变量中,Chart如下所示
function Chart() {
var self = this;
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(self);
});
}
};
Run Code Online (Sandbox Code Playgroud)
此外,您可以传递this以下内容,作为Array.prototype.forEach接受this
arr.forEach(callback[, thisArg])
Run Code Online (Sandbox Code Playgroud)
例如,
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(this);
}, this); // Pass the current object as the second parameter
}
Run Code Online (Sandbox Code Playgroud)
添加我自己的答案(使用bind):
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(this); //question: how to get Chart instead of global scope?
}.bind(this));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21801 次 |
| 最近记录: |