typescript 如何从打字稿的方法类中的函数访问类成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13430956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access class member from function in method class in typescript
提问by Flores
I have this typescript code:
我有这个打字稿代码:
module MyPage {
export class MyVm {
ToDo : string;
Load() {
//can access todo here by using this:
this.ToDo = "test";
$.get("GetUrl", function (servertodos) {
//but how do I get to Todo here??
this.ToDo(servertodos); //WRONG ToDo..
});
}
}
}
The question is, how do I access the todo member field in the $.get callback?
问题是,如何访问 $.get 回调中的 todo 成员字段?
回答by Fenton
TypeScript also supports arrow function that preserve lexical scoping. Arrow functions result in similar code to Jakub's example but are neater as you don't need to create the variable and adjust usage yourself:
TypeScript 还支持保留词法范围的箭头函数。箭头函数产生与 Jakub 示例类似的代码,但更简洁,因为您不需要自己创建变量和调整用法:
Here is the example using an arrow function:
这是使用箭头函数的示例:
$.get("GetUrl", (todos) => {
this.ToDo(todos);
});
回答by Jakub Konecki
The same way you do it in javascript
和你在javascript中做的一样
export class MyVm {
ToDo : string;
Load() {
//can access todo here by using this:
this.ToDo = "test";
var me = this;
$.get("GetUrl", function (todos) {
//but how do I get to Todo here??
me.ToDo(todos); //WRONG ToDo..
});
}
}
回答by Please_Dont_Bully_Me_SO_Lords
Fenton is right.
芬顿是对的。
But you can also do this:
但你也可以这样做:
mycallback(todos, self) { self.todo(todos)); }
$.get('url', mycallback(todos, this));