继承

180 阅读1分钟

原型链实现继承

缺点:父类中的引用数据类型,会被所有子类共享

Son.prototype = new Father()

构造函数继承

缺点:子类无法使用父类原型上的属性和方法

function Son() {
    Father.call(this)
}

组合继承

function Son() {
    Father.call(this)
}
Son.prototype = new Father()

原型式继承

缺点:父类中的引用数据类型,会被所有子类共享

const parent = {...};
function create(parent){
    function Fn(){}
    Fn.prototype = parent
    return new Fn()
}
const son = create(parent)

寄生式继承

const parent = {...};
function create(parent){
    const obj = Object.create(parent)
    // obj[key] = ...引用类型
    return obj
}
const son = create(parent)

寄生组合式继承

function Son() {
    Parent.call(this)
}
function inheritPrototype(Son, Parent) {
    const prototype = Object.create(parent.prototype)
    prototype.constructor = son
    son.prototype = prototype
}
Tiger.prototype.__proto__ = Animal.prototype
Tiger.prototype = Object.create(Animal.prototype)
改变tiger的constructor
Tiger.prototype = Object.create(Animal.prototype,{constructor:{value:Tiger}})
  • 测试代码
function Animal() {}
Animal.prototype.say = function() {}

function Tiger() {}
// Tiger.prototype = Object.create(Animal.prototype)
Tiger.prototype = Object.create(Animal.prototype,{constructor:{value:Tiger}})
console.log(new Tiger().constructor)
console.log(new Tiger().say)

补充基础

Function.__proto__ === Object.__proto__ === Function.prototype
Object.__proto__.__proto__ === Object.prototype