执行期间代码中的“ this”与“ this”不匹配

用户名

我们已经知道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,thisFooEditoritem的实例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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章