共翁号
共翁号 > 科普 > js如何实现继承

js如何实现继承

原创2025-06-21 00:07:30

在JavaScript中实现继承有几种常见的方法:

构造函数继承

通过在子类构造函数中调用父类构造函数,并将子类实例的`this`绑定到父类构造函数上,实现属性继承。

```javascript

function Parent() {

this.name = "Parent";

}

Parent.prototype.sayName = function() {

console.log(this.name);

}

function Child() {

Parent.call(this); // 继承属性

this.type = "Child";

}

```

原型链继承

将父类的实例作为子类的原型,使得子类实例可以访问父类原型上的属性和方法。

```javascript

function Parent() {

this.name = "Parent";

}

Parent.prototype.sayName = function() {

console.log(this.name);

}

function Child() {}

Child.prototype = new Parent(); // 继承方法

```

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

结合了构造函数继承和原型链继承的优点,既能够继承父类的属性,也能够继承父类原型上的方法。

```javascript

function Parent() {

this.name = "Parent";

}

Parent.prototype.sayName = function() {

console.log(this.name);

}

function Child() {

Parent.call(this); // 继承属性

this.type = "Child";

}

Child.prototype = new Parent(); // 继承方法

Child.prototype.constructor = Child; // 修复构造函数指向

```

Class继承

使用ES6的`class`关键字定义类,并通过`extends`关键字实现继承。

```javascript

class Parent {

constructor() {

this.name = "Parent";

}

sayName() {

console.log(this.name);

}

}

class Child extends Parent {

constructor() {

super();

this.type = "Child";

}

}

```

对象冒充(寄生式继承)

创建一个新对象,将其原型设为父类的一个实例,然后在新对象上定义方法。

```javascript

function createObj(o) {

function F() {}

F.prototype = o;

return new F();

}

var parent = {

name: "Parent"

};

var child = createObj(parent);

child.sayName = function() {

console.log(this.name);

}

```

寄生组合式继承

通过借用构造函数和原型链的方式,实现属性和方法的继承,同时避免调用两次父类构造函数。

```javascript

function inheritPrototype(subType, superType) {

var prototype = Object.create(superType.prototype);

prototype.constructor = subType;

subType.prototype = prototype;

}

function Parent() {

this.name = "Parent";

}

Parent.prototype.sayName = function() {

console.log(this.name);

}

function Child() {

Parent.call(this);

this.type = "Child";

}

inheritPrototype(Child, Parent);

```

以上是JavaScript中实现继承的几种常见方法。每种方法都有其优缺点,选择合适的方法取决于具体的应用场景和需求

返回:科普

相关阅读

    最新文章
    猜您喜欢
    热门阅读