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
}
My Problem is in the Dups.prototype.onClick function. Any ideas how to elegantly access the Dups instances “this” other than passing “this” (the clicked element) manually, so “this” in the prototype.onClick is the desired one, like so:
...
$el.on("click", function(){this.onClick(this)})
....
It works but I am wondering if there is a better way.
You can use
$.proxyas a portable implementation ofbind:$.proxygives you a new function that executes with the specifiedthis:The standard
bindmethod on function objects does the same thing (and more) but isn’t available everywhere.Then you could get the clicked element through the passed
eventif you needed it:Demo (open your console please): http://jsfiddle.net/ambiguous/K2BuX/