js 函数继承与类继承的区别是什么?
一、 语法差异
1、函数继承(原型链 / 构造函数组合)
通过构造函数和原型链实现,依赖 prototype
和 this
关键字。函数继承是一种通过函数来创建和扩展对象的方式,通常也被称为构造函数继承。它主要基于函数作为模板创建对象的逻辑。
-
原理:通过调用一个函数(构造函数)来创建一个新对象,然后在构造函数内部添加一些属性和方法。
// 父构造函数 function Animal(name) { this.name = name; } // 原型方法 Animal.prototype.speak = function() { return `${this.name} makes a sound.`; }; // 子构造函数 function Dog(name, breed) { // 继承父类属性 Animal.call(this, name); this.breed = breed; } // 继承父类原型方法
// Dog.prototype = new Animal()
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 子类特有方法
Dog.prototype.bark = function() {
return `${this.name} barks!`;
};
const dog = new Dog("Buddy", "Labrador");
console.log(dog.speak()); // "Buddy makes a sound."
console.log(dog.bark()); // "Buddy barks!"
2、类继承(ES6)
// 父类 class Animal { constructor(name) { this.name = name; } speak() { return `${this.name} makes a sound.`; } } // 子类 class Dog extends Animal { constructor(name, breed) { super(name); // 调用父类构造函数 this.breed = breed; } bark() { return `${this.name} barks!`; } } const dog = new Dog("Buddy", "Labrador"); console.log(dog.speak()); // "Buddy makes a sound." console.log(dog.bark()); // "Buddy barks!"
3、总结
总的来说,函数继承更倾向于创建独立的、有不同属性的对象,而类继承则更适合创建具有共享属性的对象。在现代JavaScript中,类继承(基于ES6 的 class
语法)成为了主流,因为它可以更清晰地表示继承关系,并提供更高级的功能。
二、 实现机制
函数继承
类继承