Javascript - instanceof

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard > Javascript - Object

1 - About

instanceof

Advertising

3 - Example

3.1 - 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

3.2 - 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

web/javascript/es/object/instanceof.txt · Last modified: 2019/02/16 17:40 by gerardnico