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

DOM Element and inheritance

instanceof works also with inheritance.

<div>A DivElement</div>
let element  = document.querySelector("div");
console.log(element instanceof HTMLDivElement);
console.log(element instanceof HTMLElement);
console.log(element instanceof Element);

Support

Iframe: Why false ?

Because an iframe creates a new browsing context.

Try this ?

myVariable instanceof mtVariable.ownerDocument.defaultView.Element





Discover More
Javascript - Class (ES6)

This article is Class in Javascript. Class was introduced in ECMAScript 2015. Before the module pattern was used to create a class-like behavior. Classes provide a simpler way to create objects and...
Javascript Console Pause On Exception
Javascript - Exception

This page is exception in Javascript Exceptions can be caught: in a try, catch, throw, finally statement. with the catch function with a promise. See catch...
Javascript - Object

object in javascript An object is a data type in Javascript. An object follows a json data structure with key that holds property value. The value may be of a variable or a function In JavaScript, a...



Share this page:
Follow us:
Task Runner