-1

Consider the Constructor functions:

function ConstructorOne(){/*.....*/}
function ConstructorTwo(){/*.....*/}

Consider the following js code:

var myInstance = new ConstructorOne();
ConstructorOne.prototype=new ConstructorTwo();
myInstance instanceof ConstructorOne; // false - why?
myInstance instanceof ConstructorTwo; // false - why?

If I instantiate after assigning a prototype to the constructor, like this, all goes ok:

ConstructorOne.prototype = new ConstructorTwo();
var myInstance = new ConstructorOne();
myInstance instanceof ConstructorOne; // true
myInstance instanceof ConstructorTwo; // true

What is the reason for this anomalous behaviour in the first example?

Here's the fiddle.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
sumeet batheja
  • 329
  • 1
  • 2
  • 13

1 Answers1

3

Because in the first example, you assign a new prototype object to the instance's constructor. Quoting the docs:

object instanceof constructor

The instanceof operator tests presence of constructor.prototype in object's prototype chain.

In this sample:

var myInstance = new ConstructorOne();
ConstructorOne.prototype = new ConstructorTwo();

... myInstance prototype chain (starting with __proto__ object) contains an old ("default") prototype of ConstructorOne. After it is completely rewritten with the second line of the code, ConstructorOne.prototype is no longer the same object that the one's in myInstance prototype chain - hence false as a result of instanceof.

raina77ow
  • 103,633
  • 15
  • 192
  • 229