this的指向
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>点击</button>
<script>
// var ldh = new Star('黎明');
// ldh.sing(); 写在前面会 报错
var that;
var _that;
class Star {
constructor(uname, age) {
that = this;
console.log(this); //
this.uname = uname;
this.age = age;
// this.sing();
this.btn = document.querySelector('button');
this.btn.onclick = this.sing;
}
sing() {
// this指向的是btn这个按钮
console.log(this);
console.log(that.uname);
}
dance() {
_that = this;
console.log(this);
}
}
var ldh = new Star('黎明');
console.log(that === ldh);
ldh.dance();
console.log(_that === ldh);
// ldh.sing();
// 1.在Es6中类没有变量提升,所以必须先定义类,才能通过类实例化对象
// 2.类里面的共有的属性和方法一定要加this使用。
// 3.constructor里面的this指实例对象 方法里面的this指的是调用者
</script>
</body>
</html>