Matthias
Matthias

Reputation: 3566

In Object-Oriented Javascript pass object member method to event handler

In Javascript I have defined an object like this:

function myObject() {
    this.x = 5;
    window.addEventListener("resize", this.resizeHandler);
}

myObject.prototype.doSomething = function() {
    alert(this.x);
}

myObject.prototype.resizeHandler = function() {
    this.doSomething();   // Here occurs error.
}

var obj = new myObject();

However I am running into the error message:

"Uncaught TypeError: undefined is not a function".

Question is "why is that?" Explanation would be great!

Upvotes: 0

Views: 297

Answers (1)

jcreamer898
jcreamer898

Reputation: 8189

You need to make sure that the context of this is correct...

function myObject() {
    this.x = 5;
    window.addEventListener("resize", this.resizeHandler.bind(this));
}

myObject.prototype.doSomething = function() {
    alert(this.x);
}

myObject.prototype.resizeHandler = function() {
    this.doSomething();   // Here occurs error.
}

Here the .bind(this) is used.

The this changes in the function used as an event handler.

Upvotes: 4

Related Questions