Reputation: 23
let's say I have a JavaScript-Class like this:
Foo.prototype = {
init: function() {
$(document).keydown(function(event) {
this.onKeyDown(event);
});
}
onKeyDown: function(event) {
alert("bar");
}
}
myObj = new Foo();
myObj.init();
This Code won't work, because in
$(document).keydown(function(event) {
this.onKeyDown(event);
});
the 'this' is of course unknown and doesn't address the object. How can i address the onkeydown-method of the Foo-Class anyhow?
I don't want exchange 'this' with 'myObj' (the name of the Object) since i may want to use the class for other Objects aswell.
Thanks for your help!
Upvotes: 1
Views: 398
Reputation:
Store it in a variable...
Foo.prototype = {
init: function() {
var self = this
$(document).keydown(function(event) {
self.onKeyDown(event);
});
}
}
or use jQuery.proxy
to return a function with the this
value bound...
Foo.prototype = {
init: function() {
$(document).keydown( $.proxy(function(event) {
this.onKeyDown(event);
}, this) );
}
}
or you can use Function.prototype.bind
, but you'll need to patch it for older browsers.
Foo.prototype = {
init: function() {
$(document).keydown( (function(event) {
this.onKeyDown(event);
}).bind(this) );
}
}
.bind()
Upvotes: 4