简体   繁体   English

function 传递如何在 typescript 中起作用?

[英]How function passing works in typescript?


class Test {
    x = 0;

    t2: T2;

    constructor() { 
        this.t2 = new T2(this.display);
    }

    display() {
        console.log(this.x);
    }

}

class T2 {
    constructor(private display: any) {

    }

    print() {
        this.display();
    }

}

let t = new Test();

t.t2.print();

When I run the above code it prints undefined instead 0 , can anyone please help me out with an explanation?当我运行上面的代码时,它打印undefined而不是0 ,谁能帮我解释一下? Thank you.谢谢你。

This is not related to TypeScript per se, but is rather a consequence of how this works in JavaScript. There are a variety of rules around how this context changes under various circumstances, you can read more about that here .这与 TypeScript 本身无关,而是this在 JavaScript 中如何工作的结果。在各种情况下,关于this上下文如何变化有多种规则,您可以在此处阅读更多相关信息

Here, the value of this is determined by the receiver of the print method, which is in this case the object t.t2 .此处, this的值由print方法的接收者确定,在本例中为 object t.t2 This means inside the print method, this is referring to an instance of the T2 class.这意味着在print方法内部, this是指T2 class 的实例。

The print method then calls this.display() where again, the value of this is determined by the receiver. print 方法然后调用this.display() ,其中this的值再次由接收者确定。 Since the receiver this time is just this again, it transitively carries over from the prior print call and is still the t.t2 object.由于这次的接收者又是this ,它从之前的print调用中传递过来,仍然t.t2 object。

And finally, since now we know that the this when you try to execute console.log(this.x) is actually the T2 instance, we note that the T2 instance does not have a property x and therefore we get undefined as expected.最后,因为现在我们知道当您尝试执行console.log(this.x)this实际上是T2实例,我们注意到T2实例没有属性x ,因此我们如预期的那样得到undefined


Here is a code snippet demonstrating the this chain.这是演示this链的代码片段。 Note how you can change the receiver of the print method and how that also changes the value of this within the method.请注意如何更改print方法的接收者以及如何在方法中更改this的值。

 class Test { constructor() { this.x = 0 this.t2 = new T2(this.display); } display() { console.log("Does this in 'display' equal 't.t2'?:", this === t.t2) console.log(this.x); } } class T2 { constructor(display) { this.display = display } print() { console.log("Does this in 'print' equal 't.t2'?:", this === t.t2); this.display(); } } let t = new Test(); t.t2.print(); // And note you can change the `this` by changing the recieving object: console.log("Swapping reciever.") t.print = t.t2;print. t;print();

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

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