this is assuming the value of Window

Asked

Viewed 37 times

1

I don’t know what’s wrong with this code. Inside the function builder EvilCircle, the this works well, but in EvilCircle.prototype.draw doesn’t work. It looks like it turns into Window.

function Shape(x, y, velX, velY, exists) {
  this.x = x;
  this.y = y;
  this.velX = velX;
  this.velY = velY;
  this.exists = exists;
}

// EvilCircle
function EvilCircle(x, y, exists) {
  Shape.call(this, x, y, 20, 20, exists);
  this.color = 'white';
  this.size = 10;
}
EvilCircle.prototype = Object.create(Shape.prototype);
EvilCircle.prototype.constructor = EvilCircle;

// Draw;
EvilCircle.prototype.draw = () => {
  console.log(this);
};
  • As explained in the questions suggested above (in particular in this answer), the problem is that the this has different behavior in Arrow functions and function's - which is one more reason not to go out using for no reason. I have seen a lot of people who think that Arrow functions are "the new way" (or worse, some think it’s the only way) to create functions, when in fact the use of function still proves necessary... The important thing is to know the difference, the implications, and evaluate when to use one or the other

  • Aaaata. Thank you!

1 answer

1

This is happening because you are using a Arrow Function, whose this Binding has lexical functioning. This means that the this shall not refer to the EvilCircle, but yes to the this of the higher scope which, in that case, is window.

Learn more in this other question. To documentation can also be clarifying in this regard.

To correct, then use a function expression:

EvilCircle.prototype.draw = function() {
  console.log(this);
  console.log(this instanceof EvilCircle); //=> true
};

About object-oriented programming in Javascript, the operation will always be prototypical. But it is worth using the new class syntax, introduced in Ecmascript 2015 (ES6) to simplify its code, mainly in the part related to inheritance.

class Shape {
  constructor(x, y, velX, velY, exists) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.exists = exists;
  }
}

class EvilCircle extends Shape {
  constructor(x, y, exists) {
    // Chama o construtor da classe pai:
    super(this, x, y, 20, 20, exists);

    this.color = 'white';
    this.size = 10;
  }

  draw() {
    console.log(this);
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.