JavaScript 中实现继承的 6 种方式包括:
- 原型链继承
- 借用构造函数继承
- 组合继承(原型链 + 借用构造函数)
- 原型式继承
- 寄生式继承
- 寄生组合式继承
下面是每种方式的详细代码示例:
1. 原型链继承
javascriptfunction Parent() { this.name = 'Parent'; this.play = [1, 2, 3]; } function Child() { this.type = 'Child'; } Child.prototype = new Parent(); // Child 继承 Parent let child1 = new Child(); let child2 = new Child(); console.log(child1.name); // Parent console.log(child1.play === child2.play); // true
2. 借用构造函数继承
javascriptfunction Parent() { this.name = 'Parent'; this.play = [1, 2, 3]; } function Child() { Parent.call(this); // 借用 Parent 构造函数 this.type = 'Child'; } let child1 = new Child(); let child2 = new Child(); console.log(child1.name); // Parent console.log(child1.play === child2.play); // false
3. 组合继承(原型链 + 借用构造函数)
javascriptfunction Parent() { this.name = 'Parent'; this.play = [1, 2, 3]; } function Child() { Parent.call(this); // 借用 Parent 构造函数 this.type = 'Child'; } Child.prototype = new Parent(); // Child 继承 Parent 的原型链 Child.prototype.constructor = Child; // 修复构造函数指向 let child1 = new Child(); let child2 = new Child(); console.log(child1.name); // Parent console.log(child1.play === child2.play); // true
4. 原型式继承
javascriptfunction object(o) { function F() {} F.prototype = o; return new F(); } let parent = { name: 'Parent', play: [1, 2, 3] }; let child = object(parent); child.type = 'Child'; console.log(child.name); // Parent console.log(child.play === parent.play); // true
5. 寄生式继承
javascriptfunction createAnother(original) { let clone = object(original); // 通过原型式继承创建对象 clone.sayHello = function() { console.log('Hello from clone'); }; return clone; } let parent = { name: 'Parent', play: [1, 2, 3] }; let child = createAnother(parent); child.type = 'Child'; console.log(child.name); // Parent console.log(child.play === parent.play); // true child.sayHello(); // Hello from clone
6. 寄生组合式继承
javascriptfunction inheritPrototype(child, parent) { let F = function() {}; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; } function Parent() { this.name = 'Parent'; this.play = [1, 2, 3]; } function Child() { Parent.call(this); this.type = 'Child'; } inheritPrototype(Child, Parent); let child1 = new Child(); let child2 = new Child(); console.log(child1.name); // Parent console.log(child1.play === child2.play); // false
以上示例展示了 JavaScript 中实现继承的 6 种方式。每种方式都有其特点和应用场景,可以根据具体需求选择合适的方式来实现继承。