为什么这个点击后控制台显示的不是‘刘德华’,而是empty string?
<body>
<button>点击button>
<script>
class Star{
constructor(name){
this.name = name;
this.btn = document.querySelector('button');
this.btn.onclick = this.sing;
}
sing(){
console.log(this.name);
}
}
var ldh = new Star('刘德华');
script>
body>
这里涉及this指向,谁调用了sing方法,谁就是sing里面的this,this.btn.onclick = this.sing
调用这个事件的就是this.btn,此时sing输出的就是this.btn.name,所以是空
送你个张学友
constructor(name){
this.name = name;
this.btn = document.querySelector('button');
this.btn.name = '张学友' // 这里btn加上name,就会输出
this.btn.onclick = this.sing;
}
如果你爱的是刘德华,那就刘德华跟张学友都给你
constructor(name){
this.name = name;
this.btn = document.querySelector('button');
this.btn.name = '张学友'
this.btn.onclick = this.sing;
this.sing() // 这个就可以输出刘德华
}
问题在于点击并没有绑定事件