mar*_*ria 14 javascript angular2-directives angular
如何this.firms在数据中调用forEach()?
我知道如何在Angular1中执行此操作,但不知道我在Angular 2中的当前项目.
目前它在forEach之外工作正常,但不在内部.
console.log(this.firms[0].name); // works
var a = 0;
console.log("--------------");
data.forEach(function (eachObj) {
console.log("firms check!");
console.log(this.firms); // not working
a = a + eachObj.income;
eachObj.name = this.firms[data.firmid - 1].name; // wont work
});
Run Code Online (Sandbox Code Playgroud)
错误:
Cannot read property 'firms' of undefined
Run Code Online (Sandbox Code Playgroud)
Era*_*hel 33
上下文this不会被注入的匿名函数注入forEach().这this就是未定义的原因.
您可以使用arrow function,如果你正在使用ES6的特性,因为它使在功能的背景下:
data.forEach(eachObj => {
console.log("firms check!");
console.log(this.firms);
a = a + eachObj.income;
eachObj.name = this.firms[data.firmid - 1].name;
});
Run Code Online (Sandbox Code Playgroud)
或者直接绑定上下文:
data.forEach(function (eachObj) {
console.log("firms check!");
console.log(this.firms);
a = a + eachObj.income;
eachObj.name = this.firms[data.firmid - 1].name;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
编辑:
正如zeroflagL所提到的,您可以简单地将上下文传递给forEach():
data.forEach(function (eachObj) {
console.log("firms check!");
console.log(this.firms);
a = a + eachObj.income;
eachObj.name = this.firms[data.firmid - 1].name;
}, this);
Run Code Online (Sandbox Code Playgroud)