Javascript 从原型功能中访问实例,而不是通过;这";可能的

Javascript 从原型功能中访问实例,而不是通过;这";可能的,javascript,jquery,this,prototype,Javascript,Jquery,This,Prototype,我的问题是Dups.prototype.onClick函数。除了手动传递“this”(单击的元素)之外,还有其他方法可以优雅地访问Dups实例“this”,因此prototype.onClick中的“this”是所需的,如下所示: var dups = new Dups($("#el")) function Dups($el) { this.value = 23 $el.on("click", this.onClick) } Dups.prototype.onClick = functi

我的问题是Dups.prototype.onClick函数。除了手动传递“this”(单击的元素)之外,还有其他方法可以优雅地访问Dups实例“this”,因此prototype.onClick中的“this”是所需的,如下所示:

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
}
它可以工作,但我想知道是否有更好的方法。

您可以将其用作以下内容的可移植实现:

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

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

描述:获取一个函数并返回一个始终具有特定上下文的新函数

函数对象上的标准
bind
方法做了同样的事情(甚至更多),但并不适用于任何地方

然后,如果需要,可以通过传递的
事件
获取单击的元素:

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

演示(请打开控制台):

您可以使用
jQuery.proxy
获取一个函数,该函数通过绑定到对象的
调用您的函数

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

更新了我的问题,因为有一些逻辑错误
Dups.prototype.onClick = function(event) {
    // event.target is what was clicked
}
$el.on("click", $.proxy(this, 'onClick')