我正在类的方法之一中使用 forEach 迭代数组。我需要访问 forEach 内的类的实例,但是this未定义。
var aGlobalVar = {};
(function () {
"use strict";
aGlobalVar.thing = function() {
this.value = "thing";
}
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(function(d) {
console.log(d);
console.log(this.value);
});
}
})();
var rr = new aGlobalVar.thing();
rr.amethod();
我正在这里做一个小提琴:http://jsfiddle.net/NhdDS/1/ http://jsfiddle.net/NhdDS/1/ .
在严格模式下如果调用函数not通过属性引用而不指定内容this
应该是,它是undefined.
forEach
(spec https://tc39.github.io/ecma262/#sec-array.prototype.foreach | MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) 允许您说出什么this
应该是,这是您传递给它的(可选)第二个参数:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(function(d) {
console.log(d);
console.log(this.value);
}, this);
// ^^^^
}
交替,箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions2015 年被添加到 JavaScript 中。由于箭头关闭this
,我们可以为此使用一个:
aGlobalVar.thing.prototype.amethod = function() {
data.forEach(d => {
console.log(d);
console.log(this.value);
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)