<body>
<button>按钮</button>
<script>
var that;
class Star {
constructor(uname ,age){
that = this;//this指向调用者,这里指向ldh,用全局变量that来存储指向的实例化对象
this.uname=uname;
this.age=age;
this.btn=document.querySelector('button');
this.btn.onclick=this.sing;//此时this指向btn
}
sing(){
console.log(this);//this在没点击按钮前指向ldh,在点击按钮后指向btn
console.log(this.uname)//在未点击之前指向刘德华的uname,在点击后,this指向btn,没有uname
console.log(that.uname);//that指向constructor返回的实例对象,这里是ldh
}
}
var ldh = new Star('刘德华','44');
ldh.sing();
</script>
</body>
js、ES6关于类中this指向问题的解释案例
最新推荐文章于 2022-10-20 23:48:55 发布