JavaScript 继承都有哪些方法?
在JavaScript中,继承是一个用来使一个类(子类)能够获取另一个类(父类)的属性和方法的机制。以下是在JavaScript中实现继承的几种方法:1. 原型链继承原型链继承是将子类的原型对象设置为父类的一个实例,从而实现继承。function Parent() { this.parentProperty = true;}Parent.prototype.getParentProperty = function() { return this.parentProperty;};function Child() { this.childProperty = false;}// 继承ParentChild.prototype = new Parent();var child = new Child();console.log(child.getParentProperty()); // true2. 构造函数继承构造函数继承通过在子类的构造函数中调用父类构造函数实现继承,并使用 .call()或 .apply()方法将子类的 this绑定到父类上。function Parent(name) { this.name = name;}function Child(name) { Parent.call(this, name);}var child = new Child('Alice');console.log(child.name); // Alice3. 组合继承(原型链 + 构造函数继承)组合继承结合了原型链继承和构造函数继承的优点,即子类的原型被设置为父类的一个实例,并且父类构造函数被用来增强子类实例。function Parent(name) { this.name = name; this.colors = ['red', 'blue', 'green'];}Parent.prototype.sayName = function() { console.log(this.name);};function Child(name, age) { Parent.call(this, name); this.age = age;}Child.prototype = new Parent();Child.prototype.constructor = Child;Child.prototype.sayAge = function() { console.log(this.age);};var child1 = new Child('Alice', 10);child1.colors.push('yellow');console.log(child1.name); // Aliceconsole.log(child1.age); // 10console.log(child1.colors); // ['red', 'blue', 'green', 'yellow']4. 原型式继承原型式继承是基于已有的对象创建新对象,使用 Object.create方法实现。var parent = { name: "Bob", getName: function() { return this.name; }};var child = Object.create(parent);child.name = "Alice";console.log(child.getName()); // Alice5. 寄生式继承寄生式继承创建一个封装继承过程的函数,这个函数在内部以某种方式增强对象然后返回。function createAnother(original) { var clone = Object.create(original); clone.sayHi = function() { console.log('Hi'); }; return clone;}var person = { name: 'Bob', getName: function() { return this.name; }};var anotherPerson = createAnother(person);anotherPerson.sayHi(); // Hi6. 寄生组合式继承寄生组合式继承通过使用寄生式继承来继承父类的原型,并将结果指定给子类的原型。function inheritPrototype(childObj, parentObj) { var prototype = Object.create(parentObj.prototype); prototype.constructor = childObj; childObj.prototype = prototype;}function Parent(name) { this.name = name;}Parent.prototype.sayName = function() { console.log(this.name);};function Child(name, age) { Parent.call(this, name); this.age = age;}inheritPrototype(Child, Parent);Child.prototype.sayAge = function() { console.log(this.age);};var child = new Child('Alice', 10);child.sayName(); // Alicechild.sayAge(); // 10