mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-29 14:36:22 +00:00
918 B
918 B
id | title |
---|---|
54c58f54-526f-4838-92c5-1a70d6b17a3c | JavaScript Instanceof Operator |
Description
Sometimes you want to know whether an object
was derived from a specific class. To
do this one can use the instanceof
operator.
Syntax
class Parent {
constructor(name, parentChild = "Parent") {
this.parentChild = parentChild;
this.name = name;
}
speak(line) {
console.log(`${this.parentChild} ${this.name} says '${line}'`);
}
}
class Child extends Parent {
constructor(name) {
super(name, "Child");
}
}
let parent = new Parent("Father");
let child = new Child("Gregory");
console.log(parent instanceof Parent); // true
console.log(parent instanceof Child); // false
console.log(child instanceof Parent); // true
console.log(child instanceof Child); // true