user10025500
user10025500

Reputation:

Instance of keyword in Javascript

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?

Upvotes: 1

Views: 104

Answers (2)

user10025500
user10025500

Reputation:

Ok I got it.

Here is the prototype chain.

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

Upvotes: 1

Andrei Yanovich
Andrei Yanovich

Reputation: 66

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.

Upvotes: 1

Related Questions