function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // 继承属性
}
// 设置 Dog 的原型为 Animal 的实例
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 恢复构造函数指针
// 重写speak方法
Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};
const dog = new Dog("Rex");
dog.speak(); // 输出 "Rex barks."
console.log(dog.constructor === Dog); // 输出: false
console.log(dog.constructor === Animal); // 输出: true