I'm not sure exactly how to phrase my question, so let me present an example:
function foo() {
window.addEventListener("keydown", function(event) {
bar(event.keycode);
}
foo.prototype.bar = function (keycode) {
//code
}
I've tried using this.bar()
, but that results in using the window
as this
. Is there a way to do this, or will I have to call another initialize method manually?
I'm not sure exactly how to phrase my question, so let me present an example:
function foo() {
window.addEventListener("keydown", function(event) {
bar(event.keycode);
}
foo.prototype.bar = function (keycode) {
//code
}
I've tried using this.bar()
, but that results in using the window
as this
. Is there a way to do this, or will I have to call another initialize method manually?
3 Answers
Reset to default 8Bind this.bar
to this
before you pass it.
function foo() {
window.addEventListener("keydown", this.bar.bind(this), false);
}
foo.prototype.bar = function (event) {
console.log(event.keyCode);
}
demo http://jsfiddle.net/2tee4/
An alternative solution if you don't have Function.prototype.bind
available*, and you're unwilling to add extra functions to Function.prototype
would be to close over the call to this.bar
:
function foo() {
var self;
self = this;
window.addEventListener('keydown', function (e) {
self.bar(e);
}, false);
}
foo.prototype.bar = function (e) {
console.log(e.keyCode);
}
* although your use of addEventListener
without attachEvent
leads me to believe that Function.prototype.bind
would be an acceptable choice
Additionally, libraries such as jQuery
may include their own form of bind
, jQuery's is jQuery.proxy
.
If your intention is to add a new listener for every foo
created, another option is to make foo
implement the EventListener interface, and simply pass this
in place of the handler.
function Foo() {
window.addEventListener("keydown", this, false);
}
Foo.prototype.bar = "foobar";
Foo.prototype.handleEvent = function(e) {
console.log(e.type); // "mousedown" (for example)
console.log(this.bar); // "foobar"
};
new Foo();
Note that this only works with addEventListener()
.
DEMO: http://jsfiddle.net/k93Pr/