javascript - 无法从构造函数调用方法

标签 javascript typescript

从同一个类中的构造函数调用私有(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/

相关文章:

typescript - 将 Uglify 与 TypeScript 和 Webpack 2 结合使用

typescript - 如何从文件中获取所有接口(interface)名称? ( typescript )

javascript - 测量滚动最准确的方法是什么?

javascript - 在 Vue App 上使用 FieldValue 增加 Firestore 的值(value)

javascript - 无法读取React中未定义的属性 'params'

html - 如何更新 Bootstrap 进度条。

javascript - 当对象类型不匹配时,对于泛型函数不会出现编译错误

是否存在 TypeScript 错误?声明仅在以特定格式编写时有效

javascript - 使用 D3 将纬度/经度放置在方位 Angular 等积 map 上

javascript - 如何批准 Firebase 的用户注册?