1

How does rect is an instance of Shape? Shape constructor is not on the prototype chain of rect.

rect.__proto__ : Rectangle.prototype
Rectangle.prototype : Object.prototype

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

What are the conditions for an object to be an instance of a Constructor?

3
  • 1
    It's not the constructor that's important, it's the prototype, and the Shape prototype is put on the prototype chain of Rectangle by the code you posted. Commented Jul 18, 2018 at 12:31
  • Tnx @Pointy, but there are two points that makes me vague.1,constructor property is changed 2, Object.create() doesn't link to Shape.prototype rather creates a copy of Shape prototype. Commented Jul 18, 2018 at 12:35
  • 2
    No, Object.create(Shape.prototype) creates a new object with Shape.prototype as its prototype link. It does not create a copy of the Shape prototype; read the documentation. Commented Jul 18, 2018 at 12:38

2 Answers 2

1

The instanceof operator tests that the constructor.prototype (Rectangle for example) is in object's prototype chain.

rect instanceof Rectangle

Is true because:

Object.getPrototypeOf(rect) === Rectangle.prototype

Please see more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

Also, you can trace this logic in the standard: https://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype-@@hasinstance:

v instanceof F

evaluates as

F[@@hasInstance](v)

In the same time https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance:

4. Let P be Get(C, "prototype")
7.a Let O be O.[[GetPrototypeOf]]().
7.d If SameValue(P, O) is true, return true.
Sign up to request clarification or add additional context in comments.

Comments

1

Ok I got it.

Here is the prototype chain.

rect__proto__: Rectangle. prototype
Rectangle.prototype.__proto__: Shape.prototype

Comments

Your Answer

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