I've drawn the following picture demonstrating how the objects are inherited ( function constructors are marked as blue, objects created from those constructors are marked as green):
Here is the code creating such hierarchy:
function Figure() {}
function Rect() {}
Rect.prototype = new Figure();
function Square() {}
Square.prototype = new Rect();
function Ellipse() {}
Ellipse.prototype = new Figure();
function Circle() {}
Circle.prototype = new Ellipse();
Now I want to check if new Square()
is inherited from the Rect
, so here is how I expect JavaScript engine to check it:
var s = new Square();
s instanceof Rect // ?
s.__proto__ === Rect.prototype // false
new Rect() new Figure()
s.__proto__.__proto__ === Rect.prototype // true
new Figure() new Figure()
So s instanceof Rect
should return true
. This is expected and is actually what is returned if I run the code. But then I want to check if new Circle()
is inherited from the Rect
, so I follow the same logic:
var c = new Circle();
c instanceof Rect // ?
c.__proto__ === Rect.prototype // false
new Ellipse() new Figure()
c.__proto__.__proto__ === Rect.prototype // true
new Figure() new Figure()
So, using this checking logic c instanceof Rect
should return true
, but if I actually run the code, c instanceof Rect
returns false. Am I misunderstanding the mechanism of the instanceof
operator?