hsyn
hsyn

Reputation: 21

Javascript method doesn't see object variable

var Shape = function(type)
{
    this.type = type;

    addEventListener("resize", this.align);
}

Shape.prototype.align = function()
{
    alert(this.type);
}

.

var variable = new Shape('rectangle');

When I resized, I want alert rectangle but it alerts undefined

Upvotes: 0

Views: 75

Answers (3)

Rayon
Rayon

Reputation: 36609

The value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called [MDN]

Function.prototype.bind() method creates a new function that, when called, has its this keyword set to the provided value.

var Shape = function(type) {
  this.type = type;
  addEventListener("resize", function() {
    this.align();
  }.bind(this));
  //OR addEventListener("resize", this.align.bind(this));  
}

Shape.prototype.align = function() {
  alert(this.type);
}


var variable = new Shape('rectangle');

Upvotes: 0

BenG
BenG

Reputation: 15164

you need to pass the scope to use this in the resize event.

var Shape = function(type) {
  this.type = type;
  addEventListener("resize", this.align.bind(this));
}

Shape.prototype.align = function() {
  alert(this.type);
}


var variable = new Shape('rectangle');

Upvotes: 1

Aer0
Aer0

Reputation: 3907

You need to use variable.align(), since you're creating a new object. By doing so, I get what you're asking for: An alert with 'rectangle'.

Upvotes: 0

Related Questions