【发布时间】:2014-07-25 22:47:45
【问题描述】:
是否可以创建一个替代 Array.forEach 自动将上下文“this”设置为与调用方法时相同的上下文?
例如(不工作,不知道为什么):
Array.prototype.each = function(fn) {
return this.forEach(fn, arguments.callee.caller);
}
function myFunction() {
this.myVar = 'myVar';
[1,2,3].each(function() {
console.log(this.myVar); // logs 'myVar'
});
}
【问题讨论】:
-
您为什么要这样做?对我来说似乎是一个 XY 问题......
-
所以我不必记住每次循环遍历数组时都绑定或传递“this”
-
答案显然是“否”,JavaScript 函数无法确定调用者中
this的值。这就是Function.bind()和箭头函数存在的原因。 -
@WladimirPalant 你应该回答我会接受它
-
@Kirk:已经有很多答案了,我不会重复其他人所说的。例如,thefourtheye 和我说的差不多。
标签: javascript arrays closures iteration