【问题标题】:Substitute Javascript this to Typescript将 Javascript this 替换为 Typescript
【发布时间】:2015-11-18 23:26:26
【问题描述】:

最近我决定将我的代码转换为 typescript,这导致了将 this 从 JavaScript 替换为 TypeScript 的问题。

这是我正在努力解决的代码。 打字稿:

/// <reference path="../typings/tsd.d.ts" />

class FormAjaxSubmit {

    form:JQuery;
    opt:any;

    constructor(element:string) {
        this.form = $(element);
        this.opt  = {
            boxID  : "#info",
            invData: {
                tag    : "[data-invalid]",
                tagTrue: "[data-invalid='true']"
            },
            msg    : {
                success: "",
                field  : ""
            }
        };
        // Even Listeners
        this.form
            .on('focusout', "[data-invalid]", e => {
                console.log(this); // outputs form.ajax object instead of current field with data-invalid 
                this.formVisuals(); // this method needs to be accessible too along with function's this
                e.preventDefault();
            });
    }

    private formVisuals() {
    }

}


$(() => {
    // Finally, we kick things off by creating the **App**.
    new FormAjaxSubmit("form.ajax");
});

我明白为什么会发生这种情况,因为this 被打字稿分配给主类。所以它只是在顶层创建 var _this = this 并继续在整个代码中使用,这阻止了我使用旧的 JavaScript 样式,如下所示:

$("form.ajax").on("focusout", [data-invalid], function(e) { 
     console.log(this) // it outputs the current field with data-invalid tag instead of the form object itself.
     e.preventDefault();
}

所以问题是在打字稿中替换 JavaScript this 的方法。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    TypeScript 中也存在函数表达式。它们不是“旧的 JavaScript 风格”。

    this.form.on("focusout", "[data-invalid]", function(e) { 
         console.log(this); // works
         e.preventDefault();
    });
    

    基本上,在这些情况下不要使用箭头函数。


    如果你想同时使用类和元素,那么你可以这样做:

    this.form.on("focusout", "[data-invalid]", (e) => { 
         this;     // class
         e.target; // element
    });
    

    或者,如果您想继续使用 this 作为元素而不是类,您可以这样做:

    let self = this;
    this.form.on("focusout", "[data-invalid]", function(e) {
         self; // class
         this; // element
    });
    

    我建议保留 this 作为类并使用箭头方法...它通过保持 this 的含义一致来减少混淆。

    【讨论】:

    • 这很有意义,但是如果将 this 分配给当前函数,我如何访问此函数中的类方法。如果可能,我需要同时使用两者。
    • 非常感谢。你拯救了我的一天。身边有聪明的人真是太好了。
    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多