js实现继承的三种方式

220 阅读1分钟

1.Object拓展方法

在Object的原型上增加一个继承方法

function Parent (name, age) {
    this.name = name
    this.age = age
    this.say = function () {
        console.log(this.name, this.age)
    }
}
function Child (height, sex) {
    this.height = height
    this.sex = sex
}

Object.prototype.extend = function (parObj) { // 在Object原型上定义一个继承方法,遍历需要继承的构造方法的实例属性,添加到自身对象中
    for(let key in parObj) {
        this[key] = parObj[key]
    }
}

let child = new Child(177, '男')
console.log(child.name) // undefined

child.extend(new Parent('老王', 40))
console.log(child.name) // 老王
child.say() // 老王, 40


2.使用call关键词内部改变

// 还是引用上面的父类 子类方法
function Parent (name, age) {
    this.name = name
    this.age = age
    this.say = function () {
        console.log(this.name, this.age)
    }
}
function Child (height, sex, name, age) {
    Parent.call(this, name, age) // 将Parent类中的this改成Child实例,并传入name age参数
    this.height = height
    this.sex = sex
}

let child = new Child(177, '男', '老王', 40)

console.log(child.name) // 老王
console.log(child.age) // 40
console.log(child.height) // 177
console.log(child.sex) // 男


3.原型继承


// 还是引用上面的父类 子类方法
function Parent (name, age) {
    this.name = name
    this.age = age
    this.say = function () {
        console.log(this.name, this.age)
    }
}
function Child (height, sex) {
    this.height = height
    this.sex = sex
}
Child.prototype = new Parent('老王', 40)
let child = new Child(177, '女')
console.log(child.name) // 老王
console.log(child.height) // 177
...