使用 super关键字
只需要将子类构造函数内加入super()关键字并传参进去即可,实际内部产生了以下步骤:
第一步:实例化传参给子类构造函数,构造函数内的函数会自动调用,于是调用了super方法
第二步:子类构造函数内的值传递给了super(),super实际上为调用父类构造函数,于是参数传递给了父类构造函数
第三步:父类sum方法的this指向的是父类构造函数内的值,而此时已经通过super传入了值,故不会再报错
class Father{
constructor(x,y){
this.x=x;
this.y=y;
}
sum(){
console.log(this.x+this.y);
}
}
class Son extends Father{
constructor(x,y){
super(x,y)
}
}
var son1=new Son(1,5);
son1.sum();
2.由于我们需要得到指向实例化对象的 this,所以我们需要得到构造函数内的 this,故而只需要将构造函数内的 this 赋值给一个变量,在类方法内调用时不再用 this 指明,而用赋值了指向实例化对象的变量即可解决
<body>
<button>开始吃</button>
<script>
var flag; //声明一个变量去存放
class Animal{
constructor(uname){
flag=this; //将指向实例化对象的this赋值
this.uname=uname;
this.btn=document.querySelector('button');
this.btn.addEventListener('click',this.eat)
}
eat(){
console.log(flag.uname + '正在吃骨头'); //此处使用赋值了指向实例化对象的flag去指即可
}
}
var dog=new Animal('旺财');
</script>
</body>