面试题答案
一键面试// 定义父类 Animal
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name +'makes a sound.');
};
// 定义子类 Dog
function Dog(name) {
// 调用父类构造函数初始化 name 属性
Animal.call(this, name);
}
// 设置 Dog 的原型为 Animal 的实例,建立原型链继承关系
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 新增 bark 方法
Dog.prototype.bark = function() {
console.log(this.name +'barks.');
};
// 测试代码
const myDog = new Dog('Buddy');
myDog.speak();
myDog.bark();