1.constructor中的this指向的是new出来的实例对象
创建一个公共类 Star 将constructor内的this 赋值给全局变量that 利用全等号判断that与 ldh 实例 是否相等
下面展示一些 内联代码片
。
<script>
var that;
class Star {
constructor(uname, age) {
that = this;
this.uname = uname;
this.age = age;
}
}
var ldh = new Star('刘德华')
console.log(that === ldh); //true
</script>
2.自定义的方法,一般也指向的new出来的实例对象
Star公共类中创建一个一定义方法 dance 此方法中的this 也指向new出来的实例对象
下面展示一些 内联代码片
。
<script>
var _that;
class Star {
constructor(uname, age) {
this.uname = uname;
this.age = age;
}
dance(){
_that=this
console.log(this);
}
}
var ldh = new Star('刘德华')
ldh.dance();
console.log(_that === ldh); //true
</script>
3.绑定事件之后this指向的就是触发事件的事件源
下面展示一些 内联代码片
。
当点击按钮就执行自定义方法sing 此时sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
// An highlighted block
<button>点击</button>
<script>
var that;
class Star {
constructor(uname, age) {
this.uname = uname;
this.age = age;
this.btn=document.querySelector('button');
this.btn.onclick=this.sing
}
sing (){
console.log(this); //<button>点击</button>
that=this;
}
}
var ldh = new Star('刘德华')
console.log(that === ldh); //false
</script>
想在sing方法中访问constructor里的数据需要借助于that
先将constructor里的this赋值给全局变量that 再通过that.变量名 在sing方法中访问constructor内的数据
下面展示一些 内联代码片
。
<script>
var that;
class Star {
constructor(uname, age) {
that=this;
this.uname = uname;
this.age = age;
this.btn=document.querySelector('button');
this.btn.onclick=this.sing
}
sing (){
console.log(this); //<button>点击</button>
// that=this;
console.log(that.uname);
}
}
var ldh = new Star('刘德华')
console.log(that === ldh); //true
</script>