「The this keyword evaluates to the value of the ThisBinding of the current execution context.」
「this 這個(gè)關(guān)鍵字代表的值為當(dāng)前執(zhí)行上下文的ThisBinding。」
然后再來看看MDN 對(duì)this 的定義:
「In most cases, the value of this is determined by how a function is called.」
「在大多數(shù)的情況下,this 其值取決于函數(shù)的調(diào)用方式。」
var x = 1
console.log(this.x) // 1
console.log(this.x === x) // true
console.log(this === window) // true
1
2
3
4
5
6
如果普通函數(shù)是在全局環(huán)境中被調(diào)用,在非嚴(yán)格模式下,普通函數(shù)中 this 也指向全局對(duì)象;如果是在嚴(yán)格模式下,this 將會(huì)是 undefined。ES5 為了使 JavaScript 運(yùn)行在更有限制性的環(huán)境而添加了嚴(yán)格模式,嚴(yán)格模式為了消除安全隱患,禁止了 this 關(guān)鍵字指向全局對(duì)象。
var x = 1
function fn() {
console.log(this); // Window 全局對(duì)象
console.log(this.x); // 1
}
fn();
1
2
3
4
5
6
7
8
9
使用嚴(yán)格模式后:
"use strict" // 使用嚴(yán)格模式
var x = 1
function fn() {
console.log(this); // undefined
console.log(this.x); // 報(bào)錯(cuò) "Cannot read property 'x' of undefined",因?yàn)榇藭r(shí) this 是 undefined
}
fn();
var x = 1
var obj = {
x: 2
}
function Sum(y, z) {
console.log(this.x + y + z)
}
Sum.call(obj, 3, 4) // 9
Sum.apply(obj, [3, 4]) // 9
1
2
3
4
5
6
7
8
9
10
11
12
13
情況五:bind 方法調(diào)用
調(diào)用 f.bind(someObject) 會(huì)創(chuàng)建一個(gè)與 f 具有相同函數(shù)體和作用域的函數(shù),但是在這個(gè)新函數(shù)中,新函數(shù)的 this 會(huì)永久的指向 bind 傳入的第一個(gè)參數(shù),無論這個(gè)函數(shù)是如何被調(diào)用的。
var x = 1
var obj1 = {
x: 2
};
var obj2 = {
x: 3
};
function fn() {
console.log(this);
console.log(this.x);
};
var a = fn.bind(obj1);
var b = a.bind(obj2);
fn();
// Window 全局對(duì)象
// 1
a();
// Object {x: 2}
// 2
b();
// Object {x: 2}
// 2
a.call(obj2);
// Object {x: 2}
// 2
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
26
27
28
29
30
31
32
33
在上面的例子中,雖然我們嘗試給函數(shù) a 重新指定 this 的指向,但是它依舊指向第一次 bind 傳入的對(duì)象,即使是使用 call 或 apply 方法也不能改變這一事實(shí),即永久的指向 bind 傳入的第一次參數(shù)。
An arrow function expression has a shorter syntax than a function expression and does notbind its ownthis,arguments,super, ornew.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
和普通函數(shù)不一樣,箭頭函數(shù)中的 this 指向了 obj,這是因?yàn)樗鼜纳弦粚拥暮瘮?shù)中繼承了 this,你可以理解為箭頭函數(shù)修正了 this 的指向。所以箭頭函數(shù)的this不是調(diào)用的時(shí)候決定的,而是在定義的時(shí)候處在的對(duì)象就是它的this。
本篇文章介紹了 this 指向的幾種情況,不同的運(yùn)行環(huán)境和調(diào)用方式都會(huì)對(duì) this 產(chǎn)生影響。總的來說,函數(shù) this 的指向取決于當(dāng)前調(diào)用該函數(shù)的對(duì)象,也就是執(zhí)行時(shí)的對(duì)象。在這一節(jié)中,你需要掌握:
this 指向全局對(duì)象的情況;
嚴(yán)格模式和非嚴(yán)格模式下 this 的區(qū)別;
函數(shù)作為對(duì)象的方法調(diào)用時(shí) this 指向的幾種情況;
作為構(gòu)造函數(shù)時(shí) this 的指向,以及是否 return 的區(qū)別;