我们已经知道var self = this
使用Knockout来避免事件处理程序中的问题很有用。但是,我在Typescript中观察到奇怪的行为。下面是简化的代码示例。
<i class="icon-edit" data-bind="click: $parent.GetEditForm"></i>
export class Foo
{
public ID: KnockoutObservable<Number>;
}
export class FooEditor
{
public Items: KnockoutObservableArray<Foo>;
public GetEditForm(item: Foo, event)
{
console.log(this);
console.log(item);
}
}
根据Visual Studio,this
是FooEditor
和item
的实例Foo
。但是,在执行过程中,this
和都item
引用的实例Foo
。这里的TypeScript错误吗?还是这是淘汰赛魔术的一部分?
您可以使用箭头函数在TypeScript中保留当前词法上下文,例如:
class Example {
private name = 'Example';
constructor() {
window.setTimeout( () => { alert(this.name); }, 1000);
}
}
在此示例中,this.name
将为“ Example”,因为我们使用了箭头功能:() =>
。如果您尝试使用正常功能执行相同操作,则会丢失以下内容的上下文this
:
class Example {
private name = 'Example';
constructor() {
window.setTimeout( function() { alert(this.name); }, 1000); // undefined
}
}
在后台,TypeScript引入了一个变量来存储作用域,并在函数内替代它。
var _this = this;
window.setTimeout(function () {
alert(_this.name);
}, 1000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句