JavaScript

构造函数继承方法

2020-05-13  本文已影响0人  开着五菱宏光的小白

1.ES5方法

  // 组合继承
function Person(name) {
    this.name = name;
}
function Chinese(name) {
    Person.call(this, name)
}        
function proto(child, parent) {
    child.prototype = new parent()
    child.prototype.constructor = child
}
proto(Chinese, Person)

注意点

缺点

// 寄生组合式继承
function Person(name) {
    this.name = name
}
function Chinese(name) {
    Person.call(this,name)
}
function create(prototype) {
    function Super() {}
    Super.prototype = prototype
    return new Super()
}
function proto(child, parent) {
    const prototype = create(parent.prototype)
    prototype.constructor = child
    child.prototype = prototype
}
proto(Chinese, Person)

2.ES6

class Father {
    constructor (x,y) {
        this.x = x;
        this.y = y;
    }
    sum() {
        console.log(this.x + this.y)
    }
}
class Son extends Father{
    constructor (x,y) {
        super(x,y);
    }
}
var son = new Son(1,1);
son.sum();

通过super调用父类的普通函数

上一篇 下一篇

猜你喜欢

热点阅读