语法区别
- 类语法
使用
class
关键字定义类,语法更加简洁直观,类似传统面向对象语言。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
- 原型语法
通过构造函数和
prototype
属性来定义对象和其方法。
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
继承方式区别
- 类语法
使用
extends
关键字实现继承,super
关键字用于调用父类的构造函数和方法。
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name} barks.`);
}
}
- 原型语法
通过原型链实现继承,通常使用
Object.create
或手动设置原型链。
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(`${this.name} barks.`);
};
实例化过程区别
- 类语法
使用
new
关键字直接实例化类。
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak();
dog.bark();
- 原型语法
同样使用
new
关键字实例化构造函数。
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak();
dog.bark();