Javascript 在forEach()中使用“this”
(免责声明:我正在学习JavaScript) 我有这样一个对象构造函数:Javascript 在forEach()中使用“this”,javascript,foreach,Javascript,Foreach,(免责声明:我正在学习JavaScript) 我有这样一个对象构造函数: var Palette = function() { this.colors = ["red", "green", "blue"]; this.getColorCombinations = function() { var combos = []; this.colors.forEach(function(a) { this.colors.forEac
var Palette = function() {
this.colors = ["red", "green", "blue"];
this.getColorCombinations = function() {
var combos = [];
this.colors.forEach(function(a) {
this.colors.forEach(function(b) {
if(a !== b) {
combos.push([a, b]);
}
});
});
return combos;
};
}
var p = new Palette();
alert(JSON.stringify(p.getColorCombinations()));
根据预期产出:
[“红色”、“绿色”]、[“红色”、“蓝色”]、[“绿色”、“红色”]、[“绿色”、“蓝色”]、[“蓝色”、“红色”]、[“蓝色”、“绿色”]
经过一些研究,我现在意识到这不起作用,因为在内部匿名函数中,“this”指向全局对象,而不再指向调色板实例
我的问题是,什么是“JavaScript方式”来处理这个问题?我看到类似的问题通过应用、绑定、调用或简单地将this
赋值给一个变量得到了解决,但到目前为止,我还没有发现任何例子表明哪种方式是在内部匿名函数中引用this
的最佳实践
是JSFIDLE。(为了便于文本复制,我将其修改为输出到div)将此作为第二个参数传递给
forEach
arr.forEach(callback, thisArg);
Per:
thisArg
:可选。值,在执行回调时用作此值 我必须展示它的用法,但要点是更改此调用:
this.colors.forEach(function(a) {
this.colors.forEach(function(b) {
if(a !== b) {
combos.push([a, b]);
}
});
});
为此:
this.colors.forEach(function(a) {
this.colors.forEach(function(b) {
if(a !== b) {
combos.push([a, b]);
}
});
}, this); // <- pass this as second arg
取决于您是否传输以支持旧浏览器。最好的解决方案是胖箭头函数:其次是rossipedia的答案。任何专业的js开发人员都可能熟悉所有这些工具……第三个最好的工具是
Function.prototype.bind
。
this.colors.forEach(a => {
this.colors.forEach(b => {
if(a !== b) {
combos.push([a, b]);
}
});
});