JS实现继承的6种方式

时间:2024-01-12 22:32:32
使用pretotype,call实现完美继承
父类:
fuction Animal(name){
    this.name=name||"Animal";
    this.sleep=function(){
        console.log(this.name + '正在睡觉!');
    }
}
Animal.prototype.eat=function(food){
    console.log(this.name + '正在吃:'+ food);
}
寄生组合继承:
function Cat(name){
    Animal.call(this);
    this.name=name||"Tom";
}
(function{
    var Super=fuction(){};
    Super.prototype=Animal.Pretotype;
    Cat.prototype=new Super();
})();
var cat=new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal);