使用call和原型链实现完整继承

使用call和原型链实现完整继承

● 要创建中国人、美国人,他们都有共同的属性和方法
○共同的属性:有名字、有年龄
○共同的方法:有吃饭、跑步等行为
● 所以可以抽取一个父对象,包含名字、年龄、吃饭、跑步的行为,让他们继承即可
● 代码如下:

  // 人类
        function Person(name, age) {
            // 只有当name有值并且age也有值时才加
            if (name && age) {
                this.name = name
                this.age = age
            }
        }
        Person.prototype.eat = function () {
            console.log('吃啊吃')
        }
        Person.prototype.run = function () {
            console.log('跑啊跑')
        }


        // 中国人
        function Chinese(name, age) {

            // 光这么调用还不够
            // 因为直接调用函数,函数里的this是window
            // 我需要把它里面的this,改成我当前的this
            Person.call(this, name, age)

        }
        // 为了继承,要让中国人的原型对象只想到Person的实例对象
        Chinese.prototype = new Person()
        Chinese.prototype.constructor = Chinese

        // 一定要写在原型链的继承后面
        Chinese.prototype.spring = function () {

            console.log('过春节')
        }

        // 美国人
        function American(name, age) {

            // 属性继承
            Person.call(this, name, age)
        }
        American.prototype = new Person()
        American.prototype.constructor = American

        // 创建一个中国人对象
        let lilei = new Chinese('李雷', 16)
        console.log(lilei)
        lilei.eat()
        lilei.run()
        lilei.spring()

        // 创建一个美国人
        let jim = new American('Jim Green', 16)
        console.log(jim)
        jim.eat()
        jim.run()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值