0
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 ?

1 Answer 1

2

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

1 Comment

Exactly, what I've been looking for. Thank you very much!

Your Answer

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