原型继承的理解

<script>
    function Animal(name) {
      this.name = name
    }

    Animal.prototype.eat = function () {
      console.log(this.name + ' is eating');
    }
    function Dog(name, breed) {
      // Function 实例的call()方法会以给定的 this 值和逐个提供的参数调用该函数
      // this 是 Dog 构造函数实例化对象,然后执行构造函数 (this.name=name)
      Animal.call(this, name)
      this.breed = breed
    }
    
    // 建立原型链,让 Dog 继承Animal
    Dog.prototype = new Animal()
    // 让原型对象指回Dog
    Dog.prototype.constructor = Dog

    Dog.prototype.bark = function () {
      console.log(this.name + ' is barking');
    }
    const dog = new Dog('Buddy', 'Labrador')
    console.log(dog);
    dog.eat()
    dog.bark()
  </script>

运行结果如下:

 Dog构造函数的原型对象指向Animal实例化的一个对象,通过constructor属性又将该原型对象的构造函数指回了Dog,接着给Dog的原型对象上添加了bark()方法。Dog的原型对象Animal也有一个原型对象Object,该原型对象上又挂载了一个eat()方法。所以通过实例化Dog对象可以调用eat()和bark()方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值