Question

After creating an inheritance chain with Foo.prototype = Object.create(Bar.prototype), which properties does JavaScript's instanceof use to determine that an object is an instance of a particular class?

For example:

var Fruit = function() {};

var Banana = function() {};
Banana.prototype = Object.create(Fruit.prototype);

var YellowBanana = function() {};
YellowBanana.prototype = Object.create(Banana.prototype);

console.log((new Fruit) instanceof Fruit); // true
console.log((new Banana) instanceof Fruit); // true
console.log((new YellowBanana) instanceof Banana); // true
console.log((new YellowBanana) instanceof Fruit); // true
Was it helpful?

Solution 2

Functionality equivalent to the instanceof operator could be implemented in plain Javascript like this:

function instance_of(obj, constructor) {
  var o = obj, prot=constructor.prototype;
  while(o != null && o !== Object) {
    o = Object.getPrototypeOf(o);
    if(o === prot) return true;
  }
  return false;
}

That uses the ES5 function, Object.getPrototypeOf() to access the prototype of a given object instance. getPrototypeOf is supported in all modern browsers, and javascript environments. Most older browsers relied on the __proto__ property (now deprecated/discouraged) to provide access to the same information.

OTHER TIPS

If we arrange the expression as object instanceof constructor then it checks to see if constructor.prototype is in the prototype of object.

Source: MDN

The reason these all return true is because they all have the the prototype of the specified function you're checking against

When you do

Instance instanceof TheFunction

It will look at all the prototype's of Instance and check if TheFunction.prototype is in there

From Mozilla:

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

The prototype, of course. prototype

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top