【发布时间】: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