【this指向】之二:类中的this

1.构造函数中的this

class Animal {
  constructor(type) {
    console.log(this) // this指向Animal的实例对象
    this.type = type || 'animal'
  }
  run () {
    console.log('It is running.')
  }
}
const Lily = new Animal('cat')

2.子类方法中的this

class Dog extends Animal {
  action () {
  	console.log('action>>>', this)
    this.run() // 这里可以访问父类的原因是什么?
  }
  say () {
    console.log('The dog is wangwangwang~~~')
  }
}
const lDog = new Dog()
lDog.action()

action中的this其实是指向Dog的实例对象,因为this中并没有run方法,所以根据原型链的知识,会向他的原型对象上查找。从而找到父类的Animal原型对象上的run方法。(如果对原型、原型链不了解,可以自行学习。)

3.子类构造函数中的this

class Dog extends Animal {
  constructor(name) {
    this.name = name
  }
  action () {
  	console.log()
    this.run() // 
  }
  say () {
    console.log('The dog is wangwangwang~~~')
  }
}
const lDog = new Dog('WangChai')

执行结果:Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
意思是:必须在constructor中先执行super()才可以操作this
正确写法如下:

class Dog extends Animal {
  constructor(name) {
    super('dog')
    console.log(this) // this指向dog实例对象
    this.name = name
  }
  say () {
    console.log('The dog is wangwangwang~~~')
  }
}
var lDog = new Dog('WangChai')

既然继承了Animalthis就要在执行Animal的构造函数之后才可以操作,不然就乱掉了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值