快速提问 – 如何访问“以上两级”属性?
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?
}
}
}
或者甚至可以在TypeScript(或一般的JavaScript)中访问这样的属性?
编辑答案:由于我的问题不够明确,我带来了一些关于这个问题的新信息.
通过启动程序员这是一个非常常见的问题.
这里的问题是这会改变它的上下文 – 首先它引用类Test,然后它引用我的内部函数 – Join().为了达到正确性,我们必须使用lambda表达式进行内部函数调用,或者为此使用一些替换值.
第一个解决方案是接受的答案.
其次是:
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
}
}
}
解决方法:
如果您使用fat-arrow语法,它将保留您的词法范围:
export class Test {
testVariable: string;
constructor() { }
TestFunction() {
var MyFunctions = {
Proxy: {
Join: function() {}
}
};
MyFunctions.Proxy.Join = () => {
alert(this.testVariable);
}
}
}
原文地址:https://codeday.me/bug/20190831/1774980.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。