51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

JavaScript 寄生组合式继承法

复习一下,太久远了又忘了。。

本质上其实就是使用一个空对象,使其原型指向父构造函数
然后让子构造函数的原型指向这个空对象
形成 子构造函数(原型) -> 空对象(原型) -> 父构造函数 这样的间接引用
这样既能让子构造函数需要继承的属性挂载到空对象实现属性继承,也不会造成属性被迫共享的问题(原先是将方法直接挂载载父构造函数的prototype上)

//Object.create的兼容替代
function createObject(o) {
    function Fn() { }
    Fn.prototype = o
    return new Fn()
}
//实现一个工具类,输入两个构造函数,返回一个继承的类
function inheritPrototype(SubType, SuperType) {
    //寄生组合式继承
    // SubType.prototype = Object.create(SuperType)
    SubType.prototype = createObject(SuperType)
    //还原Student原型对象的构造函数,避免输出时候错误显示为Person对象
    Object.defineProperty(SubType.prototype, 'constructor', {
        enumerable: false,
        writable: true,
        configurable: true,
        value: SubType
    })
}

function Person(name, age, friends) { this.name = name this.age = age this.friends = friends }

Person.prototype.running = function () { console.log('running'); }

Person.prototype.eating = function () { console.log('eating~') }

function Student(name, age, sno, score) { Person.call(this, name, age) this.sno = sno this.score = score }

//一键继承 inheritPrototype(Student, Person)


赞(2)
未经允许不得转载:工具盒子 » JavaScript 寄生组合式继承法