简体   繁体   English

没有箭头功能的Typescript / Angular2委托

[英]Typescript/Angular2 delegate without arrow function

Why typescript delegates result not equals: 为什么打字稿委托结果不等于:

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);

Why??? 为什么???

The difference is the arrow function. 区别在于箭头功能。 If you use the arrow function => , it binds this to the function. 如果您使用箭头功能=>它结合this给函数。

In your case 就你而言

this.array.forEach(item => this.someActionsWithItems(item));

equal to 等于

this.array.forEach(this.someActionsWithItems.bind(this));

You can refer to https://www.w3schools.com/js/js_function_closures.asp 您可以参考https://www.w3schools.com/js/js_function_closures.asp

and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM