Search code examples
javascriptmethodsjavascript-objectsdom-events

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


Solution

  • 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');