1

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!

1 Answer 1

4

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) );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.