js面向对象系列六之继承多态

关于继承,我们已经知道,子类能够完全继承父类的属性和方法

当然我们也可以在子类继承父类后进行改写相应的属性或添加相应的属性

function inherit(o) {
    function F() {}
    F.prototype = o
    return new F()
}

function inheritFS(Father,Son) {
    var p = inherit(Father.prototype)

    Son.prototype = p
    p.constructor = Son
}

//父类
function Father(name,sex) {
    this.name = name
    this.sex = sex
    this.list = ["王花花","李栓但","赵科爽"]
    this.eat = function() {
        console.log("吃大米")
    }
}

Father.prototype.study = function (x) {
    console.log(x)
}

function Son(name,sex) {
    Father.call(this,name,sex) //先继承,再改写
    this.cry = function() {
        console.log("会哭")
    }
    this.eat = function(food) {
        console.log(food)
    }
    this.list = ["李栓但","赵科爽"]
}

inheritFS(Father,Son)

var chlid1 = new Son("赵科爽","女")
var chlid2 = new Son("李栓但","男")

console.log(chlid1)
chlid1.eat('饭')
console.log(chlid2)
chlid2.eat('馒头')

可以看到子类完全的继承了父类并且也进行了对父类相应的属性进行更改,以及增加父类没有的属性,这就是多态的一个体现

这种写法Child1,和Child2之间并无太大区别,如果想让Child1,和Child2出现不同的状态才算是多态

function inherit(o) {
    function F() {}
    F.prototype = o
    return new F()
}

function inheritFS(Father,Son) {
    var p = inherit(Father.prototype)

    Son.prototype = p
    p.constructor = Son
}

//父类
function Father(name,sex) {
    this.name = name
    this.sex = sex
    this.list = ["王花花","李栓但","赵科爽"]
    this.eat = function() {
        console.log("吃大米")
    }
}

Father.prototype.study = function (x) {
    console.log(x)
}
function Son1 (name,sex) {
     Father.call(this,name,sex)
     this.beat = function() {
         console.log("老特么烦了")
     }
 }

 function Son2 (name,sex) {
     Father.call(this,name,sex)
     this.cry = function() {
         console.log("老是哭")
     }
 }

 inheritFS(Father,Son1)
 inheritFS(Father,Son2)

 var child1 =new Son1("李栓但","男")
 var child2 =new Son2("王花花","女")

 console.log(child1)
 child1.eat()
 child1.beat()
 child1.study("七岁上学")
 console.log(child2)
 child2.eat()
 child2.cry()
 child2.study("八岁上学")

改写代码后

发现child1和child2既有相同的方法eat和属性list,也有不同的方法cry和beat,这就呈现出继承多态了

封装保证继承,继承保证代码复用,多态保证可扩展性和可维护性

以上就是封装-继承-多态的全部了

接下来是面向对象和面向过程的代码实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值