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
}
}
}
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With