oz1*_*1cz 4 jquery this typescript
在TypeScript中,如果使用定义函数() => {...},则this变量将引用周围类的实例.但是如果你使用function () {...},this变量将具有旧的JavaScript解释.
有没有办法this在TypeScript函数中访问这两个变量?
在TypeScript中使用JQuery时偶尔需要这个:
class X {
private v : string;
constructor() {
$('.xyz').on('change', function() {
this.v = $(this).prop('value'); // Two different this's
})
}
}
Run Code Online (Sandbox Code Playgroud)
在代码的中心行中,第一个this应该引用类X对象,而第二个this应该引用触发事件的JQuery对象.
在change事件处理程序中,this将引用.xyz仅引发事件的元素.如果你想要一个包含X类的引用,那么你需要存储一个包含该引用的变量,如下所示:
class X {
private v : string;
constructor() {
var _x = this;
$('.xyz').on('change', function() {
_x.v = $(this).prop('value');
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
712 次 |
| 最近记录: |