JS继承

207 阅读1分钟

简单来说:js的继承就是获取存在对象已有属性和方法的一种方式。js实现继承的主要方式有:

1. 基于原型的继承

function Parent(name1){
  this.name1 = name1
}
Parent.prototype.pMethod = function(){
  console.log(this.name1)
}

function Child(name2, name1){
    Parent.call(this, name1) 
    this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype 

Child.prototype.cMethod = function(){
    console.log(this.name2)
}

总结为一个重要的JS公式:

对象.__proto__ === 其构造函数.prototype

2. 基于class的继承

ES6 中有了类的概念,可以通过 class 声明一个类,通过 extends 关键字来实现继承关系。

class Parent{
    constructor(name1){
        this.name1 = name1
    }
    
    pMethod(){
        console.log(this.name1)
    }
}

class Child extends Parent{
    constructor(name2, name1){
        super(name1) 
        this.name2 = name2
    }
    
    cMethod(){
        console.log(this.name2)
    }
}