<button type="button">我是输出son1的第一个参数</button>
<script>
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
return this.x + this.y;
}
}
var that;
class Son extends Father {
// constructor里面的this指向的是创建的实例对象
constructor(x, y) {
super(x, y);
this.x = x;
this.y = y;
this.btn = document.querySelector('button');
this.btn.onclick = this.output; //这里不需要加小括号
that = this; // 将constructor的this传递给全局变量that
}
sub(){
// 普通函数里面的this指向的是创建的实例对象
return this.x - this.y;
}
output(){
// output里面的this指向的是btn,因为是btn调用了这个方法
console.log(this); // 输出:<button type="button">我是输出son1的第一个参数</button>
console.log(this.x); // btn里面没有x这个属性,所以输出undefined
console.log(that.x); // 通过设置一个全局变量that,将constructor的this传递给了that,再输出that.x,所以点击按钮输出5
}
}
var son1 = new Son(5,6);
console.log(son1.sum());
console.log(son1.sub());
输出: