开始先推荐一篇文章,将js的继承讲述的特别全面,我就是取里面的结论,方面日后查阅
Javascript如何实现继承?

一.继承的使用方法

js里面常用的就是extends,使用方式如下:

class Father {
    constructor(name) {
      this.name = name
    }
    // 原型方法
    // 即 Person.prototype.getName = function() { }
    // 下面可以简写为 getName() {...}
    getName = function () {
      console.log('Person:', this.name)
    }
}

class child extends Father {
    constructor(name, age) {
        super(name)
        this.age = age
    }
    getAge = function () {
        console.log('Age:', this.age)
    }
}

const person = new child('Jim','28')
person.getName() // Person: Jim
person.getAge() // Age: 28

二.实现继承的方法 - 寄生组合式继承

实现继承有多种方式,我这里就选取最优的方式展示,extends也是使用的寄生组合式方法

function extend(father, child) {
    // 用 Object.create 拷贝父亲的prototype
    child.prototype = Object.create(father.prototype)
    //手动挂上构造器,指向自己的构造函数
    child.prototype.constructor = child
}

测试一下

// 测试例子
function father() {
    this.name = 'Tom';
    this.play = [1, 2, 3];
}
father.prototype.getName = function () {
    return this.name;
}

function child(friends) {
    father.call(this)
    this.friends = friends
} 

// 继承
extend(father,child)

child.prototype.getFriends = function () {
    return this.friends;
}

let person6 = new child('July');
console.log(person6.getName()); // Tom
console.log(person6.getFriends()); // July
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐