Typescript 如何从构造函数中的事件内部访问类函数?
我在typescript中向类构造函数中的ID添加了一个更改事件,在该更改事件中,我希望访问一个类函数,但在事件中“this”似乎不是类。如何从那里访问该功能Typescript 如何从构造函数中的事件内部访问类函数?,typescript,Typescript,我在typescript中向类构造函数中的ID添加了一个更改事件,在该更改事件中,我希望访问一个类函数,但在事件中“this”似乎不是类。如何从那里访问该功能 export class Document_Uploads { constructor() { $("#FormBrokerReferenceID").change(function () { = $("#FormBrokerReferenceID").val()
export class Document_Uploads {
constructor() {
$("#FormBrokerReferenceID").change(function () {
= $("#FormBrokerReferenceID").val();
//inside this event it does not work
this.Validate()
});
// works here inside constructor
this.Validate()
}
Validate() {
var valid: bool = true;
some other code
}
}
你的问题有两种解决办法 首先是让TypeScript为您处理范围:
constructor() {
$("#FormBrokerReferenceID").change( () => {
= $("#FormBrokerReferenceID").val();
// Should now work...
this.Validate()
});
// works here inside constructor
this.Validate()
}
第二个是自己处理,尽管这是手动执行TypeScript将为您完成的操作-值得知道的是,它不是魔术。如果您不想在事件中覆盖This
的含义,但也希望访问“outer”This,则此选项非常有用
constructor() {
var self = this;
$("#FormBrokerReferenceID").change(function () {
= $("#FormBrokerReferenceID").val();
// Should now work...
self.Validate()
});
// works here inside constructor
this.Validate()
}
你的问题有两种解决办法 首先是让TypeScript为您处理范围:
constructor() {
$("#FormBrokerReferenceID").change( () => {
= $("#FormBrokerReferenceID").val();
// Should now work...
this.Validate()
});
// works here inside constructor
this.Validate()
}
第二个是自己处理,尽管这是手动执行TypeScript将为您完成的操作-值得知道的是,它不是魔术。如果您不想在事件中覆盖This
的含义,但也希望访问“outer”This,则此选项非常有用
constructor() {
var self = this;
$("#FormBrokerReferenceID").change(function () {
= $("#FormBrokerReferenceID").val();
// Should now work...
self.Validate()
});
// works here inside constructor
this.Validate()
}
问题实际上是关于此的范围,因此是的副本(当然,公认的答案将帮助您-关键是使用胖箭头函数)。VTC只是为了避免重复。问题实际上是关于
此
的范围,因此是重复的(当然,公认的答案会对您有所帮助-关键是使用胖箭头功能)。职训局只是为了避免重复。