js 实现类、继承

实现类

使用原型

	function Point(x, y) {
        this.x = x
        this.y = y
    }

    Point.prototype.toAdd = function () {
        return this.x + this.y
    }
    Point.prototype.toSub = function () {
        return this.x - this.y
    }
    let p = new Point(1, 11)
    console.log(p.toAdd(), 'toAdd') //12
    console.log(p.toSub(), 'toSub') //-10

使用class

 	class Point1 {
        constructor(x, y) {
            this.x = x
            this.y = y
        }

        toAdd = function () {
            return this.x + this.y
        }

        toSub = function () {
            return this.x - this.y
        }
    }

    let p1 = new Point1(1, 11)
    console.log(p1.toAdd(), 'toAdd1') //12
    console.log(p1.toSub(), 'toSub1') //-10

实现继承

使用原型

 	function Animal(legNumber) {
        this.legNumber = legNumber
    }

    Animal.prototype.kind = "动物"
    Animal.prototype.run = function () {
        console.log(`我可以跑 我有${this.legNumber}条腿`)
    }

    function Dog(name) {
        this.name = name
        Animal.call(this, 4)
    }

    let f = function () {

    }
    f.prototype = Animal.prototype
    Dog.prototype = new f()
    Dog.prototype.kind = '狗'
    Dog.prototype.say = function () {
        console.log(`汪汪汪~ 我是${this.name},我有${this.legNumber}条腿。`)
    }

    let wangzai = new Dog('旺仔')
    wangzai.say() //汪汪汪~ 我是旺仔,我有4条腿。
    wangzai.run() //我可以跑 我有4条腿
    console.log(wangzai.kind) //狗

使用class

  class Animal1 {
        constructor(legNumber) {
            this.legNumber = legNumber
        }

        run = function () {
            console.log(`我可以跑 我有${this.legNumber}条腿`)
        }
    }

    class Cat extends Animal1 {
        constructor(name) {
            super(4);
            this.name = name
        }

        say = function () {
            console.log(`喵喵喵~ 我是${this.name},我有${this.legNumber}条腿。`)
        }
    }

    let kaiti = new Cat('凯蒂')
    kaiti.say()  //喵喵喵~ 我是凯蒂,我有4条腿。
    kaiti.run()  //我可以跑 我有4条腿
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值