js 继承方法

function Animal(name) {
    this.name = name;
}

Animal.prototype.speak = function() {
    console.log(this.name + ' makes a noise');
};

function Dog(name, breed) {
    // 实现继承
    Animal.call(this,name);
    this.breed=breed;
}
//方法1 
// Dog.prototype=Object.create(Animal.prototype);
// Dog.prototype.constructor=Dog;
//方法二
inherit(Dog,Animal)
function inherit(child,parent){
    const proto=Object.create(parent.prototype);
    child.prototype=proto;
    child.prototype.constructor=child;

}
Dog.prototype.bark=function(){
    console.log(this.name+ ' barks')
}


// 实现 Dog 继承 Animal,并添加 bark 方法
const dog = new Dog('Buddy', 'Golden');
dog.speak(); // Buddy makes a noise
dog.bark();  // Buddy barks!
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true

 

posted @ 2025-12-26 15:28  howhy  阅读(1)  评论(0)    收藏  举报