之前写了一篇关于this指向的问题,那么现在详细补充一点
之前写的: https://blog.csdn.net/sslcsq/article/details/106199901
可以结合这个以及之前写的参考对比一下
运行时:this它才是真正在运行时的环境为准 ,也就是说this是动态改变的
词法环境: 即变量和函数在定义时的环境,即为词法环境
这两点 很重要 很重要 很重要
this各种场景大集合:
a.在全局环境下:this===window===全局
b.在普通函数内:this === window
c.在构造函数内:this永远指向当前被实例化的对象
例如:f1,f2
function Fn(name='张三',age=0) {
this.name=name
this.age=age
//指向实现化的对象,分别:this===f1 //true
console.log('this:',this)
}
var f1=new Fn('ssl',20)
var f2=new Fn(‘csq’,18)
d.在对象中:
var value='React'
var obj={
value:'vuejs',
getValue:function() {
//this=== obj //true
function getValue2() {
console.log('obj内部this:',this.value) //this === window
}
getValue2()
return this.value;
}
}
obj.getValue()
e.在dom中:
<button class="btn">改变当前按钮背景色</button>
<script>
var btn=document.querySelector('.btn')
btn.onclick=function() {
console.log(this===btn)
this.style.background='#f00'
}
</script>
f.在定时器中
var value='React'
var obj={
value:'vuejs',
getValue:function() {
var _this=this;
setTimeout(function() {
console.log(this) //定时器中的this永远指向window
console.log(this.value)
},2000)
}
}
obj.getValue()
解决方案:通过保存this或箭头函数或call,apply,bind来实现
总结一下:
this:谁调用this,this就指向谁??????难道这句话真的正确吗?????
答案是对一半
看下这几个例子 就知道有时候this并不是指向调用者
var value='React';
var obj={
value:'Vuejs',
getValue:function() {
console.log(this===window)
console.log(this.value);
}
}
// obj.getValue(); // this===obj
// console.log((obj.getValue)()) //this===obj
//console.log((obj.getValue=obj.getValue)()) //this===window
//console.log((false || obj.getValue)()) //this===window
//console.log((false,obj.getValue)()) //this===window
这次的介绍中是在各大应用场合中比如计时器,对象,函数里面this的指向问题,想表达的是写概念性的东西,具体代码演示看之前this指向博文~