考虑以下TypeScript代码:
class Foo {
memberVal: string;
constructor(m: string) {
this.memberVal = m;
}
show() {
console.log("memberVal: " + this.memberVal);
}
}
let obj = new Foo("Some arbitrary value");
console.log("Direct function calling obviously works.");
obj.show();
console.log("Calling function by name also works.");
obj["show"]();
let funcRef = obj["show"];
console.log("Calling function by reference DOES NOT WORK!");
// ERROR: Cannot read property 'memberVal' of undefined
funcRef();
I am not sure why doesn't the third call work (funcRef()
).
I am aware that 'this
' changes when called from within a function, and this is why it is recommended to use arrow functions for handlers that needs access to class members. However, I don't think the above code has that issue, unless this is something internal to TypeScript/JavaScript that I am not aware of.