If you use ES6 and classes, you can use instanceof
.
class Animal {
greet() {
// Do nothing.
}
}
class Dog extends Animal {
greet() {
console.log("Woof!");
}
}
class Cat extends Animal {
greet() {
console.log("Meow!");
}
}
let dog = new Dog();
console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!
Or in ES5:
function Animal() {
}
Animal.prototype.greet = function() {
// Do nothing
}
function Dog() {
Animal.call(this);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.greet = function() {
console.log("Woof!");
}
function Cat() {
Animal.call(this);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.greet = function() {
console.log("Meow!");
}
var dog = new Dog();
console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!
Note: instanceof
is not an ES6 feature, but classes are. You can use instanceof
with ES5-style prototypes. For more info, see MDN