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



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

class classCat { 
  constructor(name) { = name;

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


var Cat = function(name) {
    obj = {}; = 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); = 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);


Iframe: Why false ?

Because an iframe creates a new browsing context.

Try this ?

myVariable instanceof mtVariable.ownerDocument.defaultView.Element

Powered by ComboStrap