浅谈对this的理解

162 阅读2分钟

this是个关键词,是个存放指针的变量。

前提是在js中,别的语言我更不清楚了:

1、 this 默认指向 是 window

[JavaScript]
纯文本查看
复制代码
1
2
3
<font style="color:rgb(79, 79, 79)"><font face="&quot;"><font style="font-size:16px">var name ='mongo';
console.log(this.name) // mongo
console.log(this) // window</font></font></font>


2、如果给元素添加了事件,当元素调用事件函数的时候, this 指向了 该 元素

[JavaScript]
纯文本查看
复制代码
1
2
3
4
5
6
<font style="color:rgb(79, 79, 79)"><font face="&quot;"><font style="font-size:16px">var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
console.log(this) // oBtn 这个对象元素
}
</font></font></font>

3、如果给元素添加了事件,而该事件函数里面又套了一层函数, 此时该元素调用 事件函数的时候, this 指向又发生了 变化, 指向了全局 window
[JavaScript]
纯文本查看
复制代码
1
2
3
4
5
6
7
var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
setTimeout(function(){
console.log(this) // window
},1000)
}


如果不包一层setTimeout,还可以加 return


[JavaScript]
纯文本查看
复制代码
1
2
3
4
5
6
7
var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
return function(){
console.log(this) // window
}
}


4、当遇到new 的时候, this 指向 了一个新的实例对

[JavaScript]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
<font style="color:rgb(79, 79, 79)"><font face="&quot;"><font style="font-size:16px">function Person(name){
this.name = name;
this.sayName = function(){
console.log(this.name)
console.log(this)
}
}
var onePerson = new Person('mongo')
onePerson.sayName(); // ‘mongo’ onePerson实例对象
</font></font></font>

5、即便new 很厉害,但是遇到 call 或者apply 也认怂了! 此时的 this 会指向 call或者apply 里面的第一个参数对象!


[JavaScript]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
<font style="color:rgb(79, 79, 79)"><font face="&quot;"><font style="font-size:16px">var name = ‘mongo’;[/size][/font][/color][/p]
function Person(name){
this.name = name;
this.sayName = function(){
console.log(this.name)
console.log(this)
}
}
var onePerson = new Person('liulian');
onePerson.sayName().call('window') // mongo 此时的this就指向了 全局window
</font></font></font>
稍稍总结一下, this 是一个存指针的变量, this指向一直在变化, 为什么会变化,应该是随着上下文执行的环境变化而变化吧! 情况大概分为四种:

1、 谁调用了此函数, 那么this 就指向谁

2、如果遇到函数里面又包了一层函数,那么 this的指向就变成全局的了

3、 如果遇到new 那么指向就是 新创建的实例对象

4、如果遇到call 或apply,那么 this 指向就是 call或apply 里面的第一个参数


原贴地址:
https://blog.csdn.net/mongo__/article/details/72818059