面试题答案
一键面试class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks.`);
}
}
在上述代码中:
Animal
类是基类,它有一个name
属性和speak
方法。Dog
类通过extends
关键字继承自Animal
类,并且添加了bark
方法。
关于原型链:
- 当创建一个
Dog
实例时,Dog
实例的__proto__
指向Dog.prototype
。 Dog.prototype
的__proto__
指向Animal.prototype
,这就建立了继承关系。所以当调用Dog
实例的speak
方法时,JavaScript引擎会先在Dog.prototype
上寻找该方法,如果找不到,就会沿着原型链到Animal.prototype
上去寻找。Animal.prototype
的__proto__
指向Object.prototype
,而Object.prototype
的__proto__
为null
,这就是原型链的终点。如果在整个原型链上都找不到对应的属性或方法,就会返回undefined
。