【问题标题】:Accessing instance from within prototype function other than through "this" possible?可以从原型函数中访问实例,而不是通过“this”?
【发布时间】:2012-03-04 00:54:46
【问题描述】:
var dups = new Dups($("#el"))

function Dups($el) {
 this.value = 23
 $el.on("click", this.onClick)
}

Dups.prototype.onClick = function(){
// usually "this" inside here refers to the instance (Dups)
// but because jquery changes "this", inside here "this" refers to the clicked element
// how can I access the Dups instances "this.value" from here?
   alert(this.value) // does not alert 23
}

我的问题出在 Dups.prototype.onClick 函数中。除了手动传递“this”(被点击的元素)之外,如何优雅地访问 Dups 实例“this”的任何想法,因此原型中的“this”是所需的,如下所示:

...
$el.on("click", function(){this.onClick(this)})
....

它有效,但我想知道是否有更好的方法。

【问题讨论】:

  • 更新了我的问题,因为有一些逻辑错误

标签: javascript jquery this prototype


【解决方案1】:

您可以将$.proxy 用作bind 的可移植实现:

function Dups($el) {
    this.value = 23;
    $el.on("click", $.proxy(this.onClick, this));
}

$.proxy 为您提供了一个使用指定的this 执行的新函数:

jQuery.proxy(函数,上下文)
返回:函数

描述:接受一个函数并返回一个新的函数,它总是有一个特定的上下文。

函数对象上的标准 bind 方法可以做同样的事情(甚至更多),但并非在任何地方都可用。

如果需要的话,你可以通过传递的event获取点击的元素:

Dups.prototype.onClick = function(event) {
    // event.target is what was clicked
}

演示(请打开您的控制台):http://jsfiddle.net/ambiguous/K2BuX/

【讨论】:

    【解决方案2】:

    您可以使用jQuery.proxy 来获取一个函数,该函数调用您的函数并将this 绑定到您的对象...

    $el.on("click", $.proxy(this, 'onClick')
    

    【讨论】:

      猜你喜欢
      • 2014-04-14
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多