instanceof operator returns false on subsequent change to inheritance chain

javascript, prototype

Solution

Prototypal inheritance can be a bit of a brain bender. I've already written a simple explanation for prototypal inheritance in the following answer and I suggest you read it: https://stackoverflow.com/a/8096017/783743

Now to answer your question. Consider the following function:

function F() {}

I can create an instance of `F` using `new` as follows:

var f = new F;

As expected `f instanceof F` returns `true`. This is because the `instanceof` operator checks for `F.prototype` in the prototype chain of `f` and returns `true` if it is there. See the answer I linked to above.

Now say I create a new function `G` as follows and set `F.prototype` to `G.prototype`:

function G() {}

F.prototype = G.prototype;

If I now evaluate `f instanceof F` again `false` is returned. This is because `F.prototype` is no longer in the prototype chain of `f` (remember that `F.prototype` is now `G.prototype`).

Now let's create a new instance of `F`:

var g = new F;

If you evaluate `g instanceof G` it'll return `true` even though `g = new F`. This is because `G.prototype` exists in the prototype chain of `g`.

This is not a bug. It's the way JavaScript works. In fact we can exploit this feature to create some really interesting functions: Instantiate JavaScript functions with custom prototypes

Problem

When a prototype is set on a constructor function, the `instanceof` operator only returns `true` until the prototype is changed. Why? ``` function SomeConstructorFunction() { } function extendAndInstantiate(constructorFn) { constructorFn.prototype = {}; //Can be any prototype return new constructorFn(); } var child1 = extendAndInstantiate(SomeConstructorFunction); console.log(child1 instanceof SomeConstructorFunction); //true var child2 = extendAndInstantiate(SomeConstructorFunction); console.log(child1 instanceof SomeConstructorFunction); //false console.log(child2 instanceof SomeConstructorFunction); //true ```

Original source

Related problems