webveuje/js/kejian/this.md
2021-03-23 10:58:10 +08:00

107 lines
2.2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# this
 首先必须要说的是this的指向在函数定义的时候是确定不了的只有函数执行的时候才能确定this到底指向谁实际上** this的最终指向的是那个调用它的对象 **
例1
```
function a(){
var user = "追梦子";
console.log(this.user); //undefined
console.log(this);  //Window
}
window.a();
//判断this跟this所处的函数没有关系结果取决于哪个对象调用的他 最外层的对象是window
```
例2
```
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
o.fn();
// fn外部是对象O访问的是this.user 即o.user => o.user的值是“追梦子”
```
例3
```
var user="pplok
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
window.o.fn();
```
例4
```
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
```
总结:
情况1如果一个函数中有this但是它没有被上一级的对象所调用那么this指向的就是window这里需要说明的是在js的严格版中this指向的不是window但是我们这里不探讨严格版的问题你想了解可以自行上网查找。
  情况2如果一个函数中有this这个函数有被上一级的对象所调用那么this指向的就是上一级的对象。
  情况3如果一个函数中有this这个函数中包含多个对象尽管这个函数是被最外层的对象所调用this指向的也只是它上一级的对象
例5
```
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); // undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
```
判断this时需要看函数调用的位置而不是我们定义函数的位置
this永远指向的是最后调用它的对象也就是看它执行的时候是谁调用的
this 遇到return 时
```
function fn()
{
this.user = '追梦子';
return
}
var a = new fn;
console.log(a.user); //undefined
```
函数return的值为对象时this就指向 这个被return的对象