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

Combining Classes and Event Listeners: `this` keyword

本文关键字:this 关键字 监听器 事件 组合      更新时间:2024-04-20

我很难回答我的问题,我认为这只是因为"类"、"这个"和其他类似的术语太通用了,无法有效地在谷歌上搜索。


考虑以下代码:

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();

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

有人知道我如何以这种方式访问类的特定实例吗?如果没有,有没有更好的方法来写这篇文章,这样我一开始就不会有这个问题?

由于方法alertProductName由事件处理程序调用,因此默认情况下,事件处理程序方法中的this指触发事件的dom元素。

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

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

另一个解决方案是使用闭包变量来引用小部件元素,例如:fiddle-如果您计划确保构造函数的原型函数,这将不起作用

这不是你想象的那样。

这很好地回答了问题
";这个";关键词工作?