Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不带箭头功能的Typescript/Angular2委托_Angular_Typescript_Delegates - Fatal编程技术网

不带箭头功能的Typescript/Angular2委托

不带箭头功能的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

为什么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 '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: