从同一个类中的构造函数调用私有(private)/公共(public)方法给我一个错误
Uncaught TypeError: this.setEventHandler is not a function at Object.Init (Init.ts:4) at :3:16
export class Init {
constructor(private connectBtn: HTMLElement) {
this.setEventHandler();
}
public setEventHandler() {
this.connectBtn.onclick = (e) => {
this.openConnectWindow();
}
}
private openConnectWindow() {
console.log("OPEN SESAME")
}
}
这是编译后的javascript
var Init = (function () {
function Init(connectBtn) {
this.connectBtn = connectBtn;
this.setEventHandler();
}
Init.prototype.setEventHandler = function () {
var _this = this;
this.connectBtn.onclick = function (e) {
_this.openConnectWindow();
};
};
Init.prototype.openConnectWindow = function () {
console.log("OPEN SESAME");
};
return Init;
}());
编辑:这是一个图书馆。
我尝试输入 var mylib = new MyLibraryName() 但我只得到“MyLibraryName 不是构造函数”。
我用 webpack 启动根对象
output: {
path: path.join(__dirname, "lib"),
filename: outputFile,
library: libraryName,
libraryTarget: "umd",
umdNamedDefine: true
},
最佳答案
将您正在调用的方法从其他方法更改为此方法
export class Init {
constructor(private connectBtn: HTMLElement) {
this.setEventHandler();
}
public setEventHandler = () => {
this.connectBtn.onclick = (e) => {
this.openConnectWindow();
}
}
private openConnectWindow = () => {
console.log("OPEN SESAME")
}
}
关于javascript - 无法从构造函数调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635822/