不使用class:
function Animal(name) {
this.name = name;
}
function Cat(name) {
Animal.call(this, name);
}
(function () {
var Super = function () {};
Super.prototype = Animal.prototype;
Cat.prototype = new Super();
})();
Cat.prototype.constructor = Cat;
var cat = new Cat();
console.log(cat instanceof Animal);//true
console.log(cat instanceof Cat);//true
console.log(Cat.prototype.__proto__ == Animal.prototype);//true
使用class:
class Animal {
constructor(name) {
this.name = name;
}
move() {}
}
class Dog extends Animal {
constructor(name, color) {
super(name);
this.color = color;
}
bark() {}
}
var dog = new Dog("naruto");
console.log(dog instanceof Animal);//true
console.log(dog instanceof Dog);//true
console.log(Dog.prototype.__proto__ === Animal.prototype);//true
参考: 幻天芒 JS实现继承的几种方式