乐闻世界logo
搜索文章和话题

JavaScript 继承都有哪些方法?

浏览7
6月24日 16:43

在JavaScript中,继承是一个用来使一个类(子类)能够获取另一个类(父类)的属性和方法的机制。以下是在JavaScript中实现继承的几种方法:

1. 原型链继承

原型链继承是将子类的原型对象设置为父类的一个实例,从而实现继承。

javascript
function Parent() { this.parentProperty = true; } Parent.prototype.getParentProperty = function() { return this.parentProperty; }; function Child() { this.childProperty = false; } // 继承Parent Child.prototype = new Parent(); var child = new Child(); console.log(child.getParentProperty()); // true

2. 构造函数继承

构造函数继承通过在子类的构造函数中调用父类构造函数实现继承,并使用 .call().apply()方法将子类的 this绑定到父类上。

javascript
function Parent(name) { this.name = name; } function Child(name) { Parent.call(this, name); } var child = new Child('Alice'); console.log(child.name); // Alice

3. 组合继承(原型链 + 构造函数继承)

组合继承结合了原型链继承和构造函数继承的优点,即子类的原型被设置为父类的一个实例,并且父类构造函数被用来增强子类实例。

javascript
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); // Alice console.log(child1.age); // 10 console.log(child1.colors); // ['red', 'blue', 'green', 'yellow']

4. 原型式继承

原型式继承是基于已有的对象创建新对象,使用 Object.create方法实现。

javascript
var parent = { name: "Bob", getName: function() { return this.name; } }; var child = Object.create(parent); child.name = "Alice"; console.log(child.getName()); // Alice

5. 寄生式继承

寄生式继承创建一个封装继承过程的函数,这个函数在内部以某种方式增强对象然后返回。

javascript
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(); // Hi

6. 寄生组合式继承

寄生组合式继承通过使用寄生式继承来继承父类的原型,并将结果指定给子类的原型。

javascript
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(); // Alice child.sayAge(); // 10
标签:JavaScript前端