如果您使用ES6和类,则可以使用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!
或者在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!
注:instanceof
不是一个ES6的特性,但类。您可以使用instanceof
与ES5样式原型。 see MDN
js是宽松打字,您应该使用'employeeType ===“manager”'而不是'employeeType ==“manager”'(REF:https://stackoverflow.com/questions/359494/哪些等于运营商与应该使用在JavaScript比较)为js宽松打字 –
,看看这个:http://blog.jeremymartin.name/2008/03/understanding-loose -typing-in.html –
不确定如何“宽松打字”是完全相关的! –