js实现继承的三种方式

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
...复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值