Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to access "two levels above" properties [closed]

Quick question - How to access "two levels above" properties? Testing example in TypeScript:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        MyFunctions.Proxy.Join() { //some made up function from other module
            //HERE
            //How can I here access testVariable property of Test class?
        }
    }
}

Or is it even possible to access such a properties in TypeScript (or JavaScript in general)?

Edit + answer: As my question was not clear enough I bring some new info about this issue. It is very commonly asked question by starting programmers.

Issue here is that this changes its context - firstly it refers to class Test, then it refers to my inner function - Join(). To achieve correctness we have to either use lambda expressions for inner function call or use some substitute value for this.

First solution is in the accepted answer.

Second is this:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        var myClassTest: Test = this;
        MyFunctions.Proxy.Join() { //some made up function from other module
            myClassTest.testVariable; //approaching my class propery in inner function through substitute variable
        }
    }
}
like image 548
OutOfSpaceHoneyBadger Avatar asked Sep 12 '25 05:09

OutOfSpaceHoneyBadger


1 Answers

If you use fat-arrow syntax, it will preserve your lexical scope:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        var MyFunctions = {
            Proxy: {
                Join: function() {}
            }
        };

        MyFunctions.Proxy.Join = () => {
            alert(this.testVariable);
        }
    }
}
like image 194
Fenton Avatar answered Sep 13 '25 18:09

Fenton