继承

95 阅读1分钟

继承

function Number(zh, mm) {
    this.zh = zh
    this.mm = mm
}
Number.prototype.sp = function () {
    console.log("普通视频");
}
function Vipnumber(zh, mm, dj) {
    this.zh = zh
    this.mm = mm
    this.dj = dj
}
Vipnumber.prototype.sp = function () {
    console.log("普通视频");
}
Vipnumber.prototype.vipsp = function () {
    console.log("会员视频");
}

vip会员包含普通会员的所有属性
以上代码有两处重复
1.vip会员中的账号密码
2.vip播放普通视频的方法

构造函数内的继承可以为

Number.call(this, zh, mm)

结果

function Number(zh, mm) {
    this.zh = zh
    this.mm = mm
}
Number.prototype.sp = function () {
    console.log("普通视频");
}
function Vipnumber(zh, mm, dj) {
    Number.call(this, zh, mm)
    this.dj = dj
}
Vipnumber.prototype.sp = function () {
    console.log("普通视频");
}
Vipnumber.prototype.vipsp = function () {
    console.log("会员视频");
}

方法继承
Number 和 Vipnumber 构造出来对象的隐式类型都指向Object的prototype,
如果使Vipnumber的隐式类型指向Number的隐式类型 当自身没有Number的方法时就会寻找Number中的方法使用

Object.setPrototypeOf(Vipnumber.prototype, Number.prototype)

改变之后即可使用Number的方法

也可以封装一个方法

function inherit(child, parent) {
    Object.setPrototypeOf(child.prototype, parent.prototype)
}

inherit(Vipnumber,Number)