【问题标题】:Combining Classes and Event Listeners: `this` keyword结合类和事件监听器:`this` 关键字
【发布时间】:2013-12-23 06:41:12
【问题描述】:

我很难回答我的问题,我认为这仅仅是因为“类”和“这个”以及其他此类术语对于有效的谷歌搜索来说过于笼统。


考虑以下代码:

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 被调用作为事件的回调。我找不到任何其他方法来从用作回调的函数中访问此类的特定 instance。看起来 Javascript 曾经有 arguments.callee 但已被弃用。

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

【问题讨论】:

  • 典型答案:在更高的范围内缓存this,例如var self = this,然后使用self 代替this
  • 或使用$.proxy()
  • 远离$productButton 之类的变量,这样您就可以在PHP 中使用JavaScript,只需使用var productButton$('body')$.ajax() 等都可以。它将节省潜在的未来头痛。只是评论。
  • @PHPglue:这是一个约定 stackoverflow.com/questions/205853/…。我没有看到任何混乱。
  • @PHPglue:在 PHP 双引号字符串中使用 jQuery $ 语法本身听起来像是一种非常糟糕的做法。我尝试使用“字符串”。 $var 。无论如何,PHP 中的 string' 而不是 "{$var}"。无论哪种方式,我都不会将 PHP 和 JS 结合起来,这是一个问题。

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


【解决方案1】:

这不是你想的那样。

这很好地回答了它
How does the "this" keyword work?

【讨论】:

    【解决方案2】:

    由于alertProductName方法是由事件处理器调用的,默认情况下,事件处理器方法内部的this指的是触发事件的dom元素。

    由于您使用的是构造函数,我首选的解决方案是使用 $.proxy() 将自定义执行上下文传递给 alertProductName 方法 - Function.bind() 执行相同但没有 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

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

    【讨论】:

    • 我不知道 $.proxy() 并且它似乎专门用于解决这个问题。 this 将继续指向我的类,而我必须使用 event.target 来重新获得对被单击的 DOM 元素的访问权限。 elclanrs 将this 缓存在另一个名为 self 的变量中的方法也有效。我可以正确使用 self.getProductName() 并继续使用 this 来访问 DOM 元素。你有什么可以告诉我的吗?
    • @TylerV。 e.targete.currentTarget 取决于您的需要
    • @TylerV。阅读答案的最后一部分......除此之外它很好
    • @TylerV。看看这个例子使用原型函数jsfiddle.net/arunpjohny/zMH3w/2
    • 我现在明白了。这非常有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2014-02-21
    相关资源
    最近更新 更多