【发布时间】: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