面试题答案
一键面试1. ES6 类语法继承中原型链的工作原理
在 ES6 类语法继承中,通过 extends
关键字实现继承。当一个类 Child
继承自另一个类 Parent
时,Child.prototype
会成为 Parent.prototype
的一个实例,从而构建出原型链。这意味着 Child
的实例可以访问 Parent
原型上定义的方法和属性。
例如:
class Parent {
constructor() {
this.parentProp = 'I am from parent';
}
parentMethod() {
return 'This is a parent method';
}
}
class Child extends Parent {
constructor() {
super();
this.childProp = 'I am from child';
}
}
const childInstance = new Child();
console.log(childInstance.parentProp);
console.log(childInstance.parentMethod());
在上述代码中,Child
继承自 Parent
,childInstance
作为 Child
的实例,可以访问 Parent
中定义的 parentProp
和 parentMethod
,这是因为 Child.prototype
是 Parent.prototype
的实例,形成了原型链。
2. super
关键字在类继承与原型链关系中的作用
在构造函数中
super
关键字用于调用父类的构造函数。在子类的构造函数中,如果要使用 this
,必须先调用 super()
。这是因为在 ES6 类继承中,子类的构造函数在调用 super()
之前,this
是未定义的。通过调用 super()
,子类构造函数会将控制权交给父类构造函数,让父类初始化一些必要的属性,然后子类再基于父类的初始化结果进行自身的属性初始化。
例如:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.name);
console.log(myDog.breed);
在 Dog
类的构造函数中,super(name)
调用了 Animal
类的构造函数,传递了 name
参数,使得 myDog
实例拥有了 name
属性,然后 Dog
类构造函数再初始化自身的 breed
属性。
在方法中
super
还可以用于调用父类的方法。当子类中定义了与父类同名的方法时,可以通过 super
来调用父类的该方法。
例如:
class Shape {
constructor(color) {
this.color = color;
}
describe() {
return `This shape is ${this.color}`;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
describe() {
return super.describe() + ` and has a radius of ${this.radius}`;
}
}
const myCircle = new Circle('red', 5);
console.log(myCircle.describe());
在 Circle
类的 describe
方法中,super.describe()
调用了 Shape
类的 describe
方法,获取了父类关于颜色的描述,然后再添加了自身关于半径的描述。这样既复用了父类的方法逻辑,又扩展了子类的功能。