The problem is with this.sayHello
. When you assign the reference to the sayHello
function on keydown, the reference to the context (object) is lost. When a key is pressed, this
refers to the Document
object as the callback is invoked as:
document.onkeydown(); // or for simplicity imagine - document.sayHello();
If you assigned the str
variable on the document
object, you would see the value logged,
document.str = "hello";
However, that is not what you'd want. You need to wrap the keydown event handler inside another function to preserve the context to that object. Two ways to go about this. You could either wrap the event handler inside another function, and preserve the reference to this.
this.init = function() {
var me = this;
document.onkeydown = function() {
me.sayHello();
};
}
Or, if you're using modern browsers, this has already been incorporated into ECMAScript 5 using the bind
function.
this.init = function() {
var me = this;
document.onkeydown = this.sayHello.bind(this);
}