将 onclick 函数扩展到 javascript 类

Extend onclick function to javascript class

本文关键字:javascript 扩展到 函数 onclick      更新时间:2023-09-26

我想在 JavaScript 类中包含 onclick 事件,但由于 onclick 是类内部的一个函数,因此 this 变量无法正常工作。

如何从 onclick 函数修改/输出this变量?

img = new image();
function image() {
    this.width = 400;
    this.height = 600;
    document.getElementById('button').onclick = function()
    {
        alert(this.width); // alerts undefined
    };
}

请参阅此处的 JSfiddle:http://jsfiddle.net/ZghRv/

您可以使用

bind() 创建一个新函数,该函数将this设置为传递给 bind() 的对象。

img = new image();
function image() {
    this.width = 400;
    this.height = 600;
    document.getElementById('button').onclick = (function()
    {
        alert(this.width); // alerts undefined
    }).bind(this);  // <---  Add bind() here to pick the value of 'this' inside onclick
}

查看 JavaScript 函数绑定以获取更多信息和交互式示例。

您还可以引用外部this

更新的小提琴:

http://jsfiddle.net/ZghRv/3/