0%

JavaScript中的this

关于this到底指向谁这件事

全局环境下的this

情况一

1
2
3
4
5
6
7
8
9
10
11
12
function f1(){
console.log(this);
}

f1(); //window

function f2(){
'use strict';
console.log(this);
}

f2(); //undefined

可见,在非严格模式下直接调用,this指向window;严格模式下,this指向undefined。

情况二

1
2
3
4
5
6
7
8
9
const obj = {
num: 10,
f: function(){
console.log(this);
console.log(this.num);
}
}

obj.f(); // 输出:{num: 10, f:f}, 10

可见,如果函数被通过上一层对象调用,this会指向上一层的对象。

情况三

1
2
3
4
5
6
7
8
9
10
const obj = {
num: 10,
f: function(){
console.log(this);
console.log(this.num);
}
}

const ff = obj.f;
ff(); // 输出:window,undefined

可见,如果函数f在window的全局环境中直接执行,this仍然指向window。

总结

在函数被执行时,如果函数中的this是被上一层对象所调用,那么this指向上一层对象,否则指向window。

上下文对象调用中的 this

情况一

1
2
3
4
5
6
7
8
9
10
11
const game = {
name: 'overwatch',
hero: {
name: 'tracer',
f: function(){
return this.name;
}
}
}

console.log(game.hero.f()); // 输出:tarcer

可见,this指向最后调用它的对象hero。

情况二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const obj1 = {
name: 'tracer',
f: function(){
return this.name;
}
}

const obj2 = {
name: 'genji',
f: function(){
return obj1.f();
}
}

const obj3 = {
name: 'doomfist',
f: function(){
const ff = obj1.f;
return ff();
}
}

console.log(obj1.f()); // 输出:tracer
console.log(obj2.f()); // 输出:tracer
console.log(obj3.f()); // 输出:undefined

聪明的你告诉我,这是为什么呢?

第一个调用,this指向obj1,结果无可厚非。

第二个调用,this仍然指向obj1。

第三个调用,this指向window,所以结果是undefined。

箭头函数中的this

一言以蔽之,箭头函数中的this指向定义箭头函数时所在的对象