推荐答案
在 JavaScript 中,可以通过以下几种方式实现继承:
原型链继承:
// www.javascriptcn.com code example function Parent() { this.name = 'Parent'; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child() { this.name = 'Child'; } Child.prototype = new Parent(); const child = new Child(); child.sayName(); // 输出: Child构造函数继承:
// www.javascriptcn.com code example function Parent(name) { this.name = name; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child(name) { Parent.call(this, name); } const child = new Child('Child'); child.sayName(); // 报错: child.sayName is not a function组合继承:
// www.javascriptcn.com code example function Parent(name) { this.name = name; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child(name) { Parent.call(this, name); } Child.prototype = new Parent(); Child.prototype.constructor = Child; const child = new Child('Child'); child.sayName(); // 输出: Child原型式继承:
// www.javascriptcn.com code example const parent = { name: 'Parent', sayName: function() { console.log(this.name); } }; const child = Object.create(parent); child.name = 'Child'; child.sayName(); // 输出: Child寄生式继承:
// www.javascriptcn.com code example function createChild(parent) { const child = Object.create(parent); child.sayHello = function() { console.log('Hello'); }; return child; } const parent = { name: 'Parent', sayName: function() { console.log(this.name); } }; const child = createChild(parent); child.sayName(); // 输出: Parent child.sayHello(); // 输出: Hello寄生组合式继承:
// www.javascriptcn.com code example function inheritPrototype(child, parent) { const prototype = Object.create(parent.prototype); prototype.constructor = child; child.prototype = prototype; } function Parent(name) { this.name = name; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child(name) { Parent.call(this, name); } inheritPrototype(Child, Parent); const child = new Child('Child'); child.sayName(); // 输出: Child
本题详细解读
原型链继承
原型链继承是通过将子类的原型指向父类的实例来实现的。这种方式的缺点是所有子类实例共享父类的引用属性,可能会导致意外的修改。
构造函数继承
构造函数继承是通过在子类构造函数中调用父类构造函数来实现的。这种方式可以避免引用属性共享的问题,但无法继承父类原型上的方法。
组合继承
组合继承结合了原型链继承和构造函数继承的优点,既通过构造函数继承属性,又通过原型链继承方法。这种方式是最常用的继承方式之一。
原型式继承
原型式继承是通过 Object.create() 方法创建一个新对象,并将新对象的原型指向现有对象。这种方式适用于不需要构造函数的场景。
寄生式继承
寄生式继承是在原型式继承的基础上,增强对象的功能。这种方式通常用于创建一个对象的增强版本。
寄生组合式继承
寄生组合式继承是组合继承的优化版本,通过减少不必要的父类构造函数调用来提高性能。这种方式是目前最理想的继承方式。
每种继承方式都有其适用场景和优缺点,开发者应根据具体需求选择合适的继承方式。