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')
既然继承了
Animal
,this
就要在执行Animal
的构造函数之后才可以操作,不然就乱掉了。