function test() {
this.str = "hello";
this.sayHello = function() {
document.write(this.str);
}
this.init = function() {
document.onkeydown = this.sayHello;
}
}
var testing = new test();
testing.init();
The above code should output “hello” on an onkeydown event.
But I get “undefined”. How can I get this to work ?
The problem is with
this.sayHello. When you assign the reference to thesayHellofunction on keydown, the reference to the context (object) is lost. When a key is pressed,thisrefers to theDocumentobject as the callback is invoked as:If you assigned the
strvariable on thedocumentobject, you would see the value logged,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.
Or, if you’re using modern browsers, this has already been incorporated into ECMAScript 5 using the
bindfunction.