面试题答案
一键面试相同点
- 创建对象实例:都可以用来创建对象实例。 例如: 构造函数方式:
function Person(name) {
this.name = name;
}
let person1 = new Person('John');
类方式:
class Person {
constructor(name) {
this.name = name;
}
}
let person2 = new Person('John');
- 都有构造逻辑:都可以在创建实例时执行初始化逻辑,如设置属性初始值。
例如上述例子中,都在创建实例时为
name
属性赋值。
不同点
- 语法:构造函数是普通的函数定义,使用函数声明或函数表达式;类是 ES6 引入的新语法糖,使用
class
关键字。 例如构造函数声明:
function Animal(type) {
this.type = type;
}
类声明:
class Animal {
constructor(type) {
this.type = type;
}
}
- 原型和原型链:构造函数的原型属性(
prototype
)直接用于定义实例共享的方法和属性;类使用class
语法,内部定义的方法自动添加到原型上。 例如构造函数添加共享方法:
function Car(make) {
this.make = make;
}
Car.prototype.drive = function() {
console.log(`Driving a ${this.make}`);
};
let car1 = new Car('Toyota');
类添加共享方法:
class Car {
constructor(make) {
this.make = make;
}
drive() {
console.log(`Driving a ${this.make}`);
}
}
let car2 = new Car('Toyota');
- 继承:构造函数实现继承相对复杂,通常使用
call
或apply
方法借用构造函数,再手动处理原型链;类使用extends
关键字和super
关键字实现继承,语法更简洁。 例如构造函数继承:
function Vehicle(type) {
this.type = type;
}
Vehicle.prototype.move = function() {
console.log(`Moving a ${this.type}`);
};
function Car(make, type) {
Vehicle.call(this, type);
this.make = make;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
Car.prototype.drive = function() {
console.log(`Driving a ${this.make} ${this.type}`);
};
let car = new Car('Toyota', 'car');
类继承:
class Vehicle {
constructor(type) {
this.type = type;
}
move() {
console.log(`Moving a ${this.type}`);
}
}
class Car extends Vehicle {
constructor(make, type) {
super(type);
this.make = make;
}
drive() {
console.log(`Driving a ${this.make} ${this.type}`);
}
}
let car = new Car('Toyota', 'car');