Javascript Typescript Uncaught TypeError:从jquery事件处理程序调用函数时不是函数
typescript新手,正在尝试找出这不起作用的原因: 我有以下类定义:Javascript Typescript Uncaught TypeError:从jquery事件处理程序调用函数时不是函数,javascript,typescript,typescript2.0,Javascript,Typescript,Typescript2.0,typescript新手,正在尝试找出这不起作用的原因: 我有以下类定义: class SliderRange { updateSliderText(lowId: JQuery, highId: JQuery) { //do some updates } constructor(public uiId: string, lowDisplay: JQuery, highDisplay: JQuery) { //register the e
class SliderRange {
updateSliderText(lowId: JQuery, highId: JQuery) {
//do some updates
}
constructor(public uiId: string, lowDisplay: JQuery, highDisplay: JQuery) {
//register the events that tie ui to the set methods here.
this.primaryUi().on("input", function () {
this.updateSliderText(lowDisplay, highDisplay);
});
this.secondaryUi().on("input", function () {
this.updateSliderText(lowDisplay, highDisplay);
});
}
private primaryUi() : JQuery {
return $(`.original#${this.uiId}`);
}
private secondaryUi(): JQuery {
return $(`.ghost#${this.uiId}`);
}
}
事件被正确激发,但当它们被激发时,浏览器会抱怨this.updateSliderText不是函数。在浏览器中,这并没有被Typescript所取代,而是引用JQuery对象(primaryUi或secondaryUi)。然而,IntelliSense正确地导航到适当的updateSliderText函数,这使我相信它应该编译成正确引用该函数的javascript
如何在jquery事件处理程序中引用属于该类的函数
谢谢。您调用
this.updateSliderText
的上下文是错误的
您需要一个箭头函数(它们正是为此而发明的),或者使用旧样式进行绑定:
this.primaryUi().on("input", () => { // Yay, cool arrow functions.
this.updateSliderText(lowDisplay, highDisplay);
});
this.primaryUi().on("input", (function() {
this.updateSliderText(lowDisplay, highDisplay);
}).bind(this)); // yay...? old-bind-style
很酷的打字脚本方法是箭头法。调用this.updateSliderText
的上下文是错误的
您需要一个箭头函数(它们正是为此而发明的),或者使用旧样式进行绑定:
this.primaryUi().on("input", () => { // Yay, cool arrow functions.
this.updateSliderText(lowDisplay, highDisplay);
});
this.primaryUi().on("input", (function() {
this.updateSliderText(lowDisplay, highDisplay);
}).bind(this)); // yay...? old-bind-style
很酷的类型脚本方法是箭头方法。如果不使用此方法,只使用updateSliderText(lowDisplay,highDisplay),发生了什么事?@TonyDong TS2304找不到名称“updateSliderText”的编译错误。如果不使用此方法,只使用updateSliderText(lowDisplay,highDisplay),发生了什么事?@TonyDong TS2304找不到name'updateSliderText'ts编译错误。酷,这正是我要找的!你有没有一个链接或名字,我可以用它来谷歌这个箭头的功能?是的,那是他们的名字。箭头功能:酷,这正是我要找的!你有没有一个链接或名字,我可以用它来谷歌这个箭头的功能?是的,那是他们的名字。箭头功能: