简体   繁体   English

在Angular Typescript中将函数作为参数传递的方式之间的差异

[英]Differences between ways to pass function as parameter in Angular Typescript

What is the difference between these two lines of code (except the fact that second line has an inline function calling "setThing"). 这两行代码之间有什么区别(除了第二行有一个调用“setThing”的内联函数的事实)。 I noticed that on the first case Angular change detection didn't run. 我注意到在第一个案例中,角度变化检测没有运行。

someObservable<Thing>.subscribe<Thing>(this.setThing) // change detection didn't run
someObservable<Thing>.subscribe<Thing>(thing => this.setThing(thing)); // change detection worked

setThing(thing :Thing) {
    this.thing = thing;
}

Assuming you are using this inside the function. 假设你在函数内部使用this In the first one you lose the lexical this , in the second you don't. 在第一个你失去了词汇this ,在第二个你没有。

Example: 例:

First one: 第一:

setThing(thing :Thing) {
    this.myTemplateThing = thing; // Since your this is not refering to the component you won't be seeing a change
}

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

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