0
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

4
  • alert(this) (or rather log it to the console), what do you see? Commented May 3, 2016 at 10:29
  • adding to BenG's answer. Under event, this will point to window Commented May 3, 2016 at 10:33
  • I see [Object object] Commented May 3, 2016 at 10:48
  • that's because of alert, try console.log instead of alert Commented May 3, 2016 at 10:49

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.