2012-03-04 60 views
0
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功能。任何想法如何优雅手动访问的DUP实例“这个”比传递其他“这”(点击的元件),因此“该”在prototype.onClick是所希望的一个,像这样:从原型函数内部访问实例而不是通过“this”可能?

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

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

+0

更新我的问题,因为那里是一些逻辑错误 – Hans 2012-03-04 00:59:37

回答

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/

1

您可以使用jQuery.proxy得到一个函数调用你的功能this绑定到你的对象...

$el.on("click", $.proxy(this, 'onClick') 
相关问题