结合类和事件监听器:`this`关键字

时间:2013-12-06 02:47:20

标签: javascript jquery oop javascript-events functional-programming

我很难回答我的问题,我认为这只是因为“类”和“这个”以及其他类似的术语对于有效的Google搜索而言过于通用。


请考虑以下代码:

function product (name) {
    var _productName;

    this.getProductName = function() {
        return this._productName;
    };

    this.alertProductName = function() {
        // This errors because `this` is a reference to the HTML <input> tag and not the class
        alert(this.getProductName());
    }

    this._productName = name;

    var $productButton = $('<input type="button" value="What is my name?" />');
        $productButton.on('click', this.alertProductName);

    $('body').append($productButton);
}

var widget = new product('Widget');

widget.alertProductName();

jQuery(或者可能是Javascript本身)正在重置 this 关键字指向的内容,一旦将product :: alertProductName作为对事件的回调调用。我找不到任何其他方法来从用作回调的函数中访问此类的特定实例。看起来Javascript曾经有过arguments.callee,但已被弃用。

有谁知道如何以这种方式访问​​类的特定实例?如果没有,是否有更好的方法来写这个,以便我没有这个问题开始?

2 个答案:

答案 0 :(得分:1)

由于方法alertProductName是由事件处理程序调用的,因此事件处理程序方法中的默认this引用了触发事件的dom元素。

由于您使用的是构造函数,我首选的解决方案是使用$.proxy() - Function.bind()将自定义执行上下文传递给alertProductName方法,但不是IE < 9 support }

function product(name) {
    var _productName;

    this.getProductName = function () {
        return this._productName;
    };

    this.alertProductName = function () {
        // This errors because `this` is a reference to the HTML <input> tag and not the class
        alert(this.getProductName());
    }

    this._productName = name;

    var $productButton = $('<input type="button" value="What is my name?" />');
    $productButton.on('click', $.proxy(this.alertProductName, this));//here use $.proxy()

    $('body').append($productButton);
}

var widget = new product('Widget');

widget.alertProductName();

演示:Fiddle

另一个解决方案是使用闭包变量来引用widget元素,例如:fiddle - 如果你打算确保构造函数的原型函数,这将不起作用

答案 1 :(得分:0)

这不是你的想法。

这很好地回答了这个问题 How does the "this" keyword work?

相关问题