Javascript - instanceof
Table of Contents
About
instanceof
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
- The constructor of a function created WITHOUT a prototype will be NOT recognized as a instanceof
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