不带箭头功能的Typescript/Angular2委托
为什么typescript委托结果不等于:不带箭头功能的Typescript/Angular2委托,angular,typescript,delegates,Angular,Typescript,Delegates,为什么typescript委托结果不等于: someProperty: any; someActionsWithItems(item: any) { this.someProperty = "test"; } //if I use this. Its OK.: this.array.forEach(item => this.someActionsWithItems(item)); // But another. It will be error because context
someProperty: any;
someActionsWithItems(item: any) {
this.someProperty = "test";
}
//if I use this. Its OK.:
this.array.forEach(item => this.someActionsWithItems(item));
// But another. It will be error because context 'this' isn't initialize (Cannot set property 'someProperty' of undefined):
this.array.forEach(this.someActionsWithItems);
为什么?区别在于箭头功能。如果使用箭头函数
=>
,它将此
绑定到函数
就你而言
this.array.forEach(item => this.someActionsWithItems(item));
等于
this.array.forEach(this.someActionsWithItems.bind(this));
你可以参考
及
区别在于箭头功能。如果使用箭头函数
=>
,它将此
绑定到函数
就你而言
this.array.forEach(item => this.someActionsWithItems(item));
等于
this.array.forEach(this.someActionsWithItems.bind(this));
你可以参考
及
我认为您需要使用bind:我认为您需要使用bind: