Javascript - instanceof

About

instanceof

instanceof works only with Object with a prototype.

e instanceof name // is roughly the same that
e.__proto__.toString() === name

See below for complete example

Example

Class

An object created from a class will always be as an instanceof its class.

class classCat { 
  constructor(name) {
    this.name = name;
   }
}

var myClassCat = new classCat("Poesie");
console.log(myClassCat instanceof classCat); // true

Function

var Cat = function(name) {
    obj = {};
    obj.name = name;
    return obj;
}

var myCat = Cat("Poesie");
console.log(myCat instanceof Cat); // false
  • The constructor of a function created WITH a prototype will be recognized as a instanceof
var Cat = function(name) {
    var obj = Object.create(Cat.prototype);
    obj.name = name;
    return obj;
}
Cat.prototype = {};

var myCat = Cat("Poesie");
console.log(myCat instanceof Cat); // true

Powered by ComboStrap