引子
在JavaScript中this的指向總是讓人很困惑,它到底指的啥?為了徹底弄清它,我們就來探討一下吧。this在不同的執(zhí)行環(huán)境,不同的用法下會有所不同,以下分幾種情況,討論this的指向。
this指向分類討論
this在全局作用域中
// global scope
foo = 'abc';
alert(foo); // abc
this.foo = 'def';
alert(foo); // def
在全局作用域/全局環(huán)境(global scope| global context)中,this指向的就是全局變量
- 在瀏覽器里,指向
window對象 - 在Node.js里,指向
global對象
this在函數(function)里
var boat = {
size: 'normal',
boatInfo: function() {
alert(this === boat);
alert(this.size);
}
};
boat.boatInfo(); // true, 'normal'
var bigBoat = {
size: 'big'
};
bigBoat.boatInfo = boat.boatInfo;
bigBoat.boatInfo(); // false, 'big'
上面這段代碼里,this指向誰?可以看到,boat對象有一個size屬性,和一個boatInfo()方法。在boatInfo()方法里,alert出this是否和boat相等,以及this所指向的size屬性。
當我們去用boat.boatInfo()時,可以看到,this和boat是相等的,this.size的值就是boat.size的值nomal
當我們創(chuàng)建一個新的對象,bigBoat,它的size屬性為big,但是bigBoat這個對象沒有boatInfo()方法,于是我們把boat.boatInfo()的方法賦給了它。然后我們調用bigBoat.boatInfo(),發(fā)現this不等于boat,this.size的值為big
this的指向改變了!
The first thing you must realise is that the value of this inside any function is never static, it is always determined every time you call a function, but before the function actually executes it’s code. The value of this inside a function is actually provided by the parent scope in which the function was called, and more importantly, how the actual function syntax was written.
要理解以上的變化,首先要明白,在任何函數中,this的指向都不是靜態(tài)的(static)。它總是在你調用一個函數,但尚未執(zhí)行函數內部代碼前被指定。(查看參考鏈接中的執(zhí)行環(huán)境的文章,這個階段,實際就是初始化變量對象,在初始化變量對象的時候,確定了this的指向)實際上,this是 被調用的函數的父作用域 提供的,更重要的是,我們要看看函數調用時是怎么寫的。
當一個函數被調用時,應該立馬看()左邊的部分。
- 如果
()左邊是一個引用(reference),那么,函數的this指向的就是這個引用所屬的對象 - 否則
this指向的就是全局對象(window|global)
function bar() {
alert(this);
}
bar(); // global - because the method bar() belongs to the global object when invoked
// 這里,this指向的是全局對象。我們先看()的左邊,是bar,
// 那么bar屬于誰呢?bar屬于全局對象,所以this指向的就是全局對象。
var foo = {
baz: function() {
alert(this);
}
}
foo.baz(); // foo - because the method baz() belongs to the object foo when invoked
// 這里,this指向的是foo,先看()左邊是baz,baz屬于foo,所以baz里的this指向的就是foo
如果代碼都那么簡單,那么this的指向也就簡單明了了。來點復雜點的看看:
var foo = {
baz: function() {
alert(this);
}
}
foo.baz(); // foo - because baz belongs to the foo object when invoked
var anotherBaz = foo.baz;
anotherBaz(); // global - because the method anotherBaz() belongs to the global object when invoked, NOT foo
// this指向全局對象,()左邊是anotherBaz,屬于全局對象
可以看到baz()中this的指向老是變來變去的。再來看看嵌套在對象里的this的指向
var anum = 0;
var foo = {
anum: 10,
baz: {
anum: 20,
bar: function() {
console.log(this.anum);
}
}
}
foo.baz.bar(); // 20 - because left side of () is bar, which belongs to baz object when invoked
// ()左邊是bar,bar屬于foo.baz,所以this就是foo.baz,this.anum = foo.baz.anum = 20
var hello = foo.baz.bar;
hello(); // 0 - because left side of () is hello, which belongs to global object when invoked
// ()左邊是hello,hello屬于全局對象,所以this指向全局對象,this.anum = window.anum = 0
再來看個例子:
const obj = {
name: 'spike',
friends: ['deer', 'cat'],
loop: function() {
this.friends.forEach( // 這個this指向obj
function( friend ) {
console.log(`${this.name} knows ${friend}`);
console.log(this === global); // 在node.js環(huán)境下,全局對象為global
}
)
}
}
obj.loop();
// ()左邊是loop,屬于obj,所以loop函數中的this指向obj
輸出
$ node test
undefined knows dear
true
undefined knows cat
true
可以看到,在forEach中的this并不是期待的那樣指向obj,而是指向全局對象了
可以用上面提到的,還是看()左邊,在forEach中,()左邊是function,而不是一個引用, 所以this指向的就是全局對象
這里其實我也有點迷惑,當不明白Scope的結構時候,可以通過在瀏覽器中運行代碼,去調試面板查看函數執(zhí)行時的作用域變化。
在構造函數里的this指向
當使用new關鍵字去執(zhí)行構造函數時,構造函數中的this指向的的就是新建的那個對象實例。
var savedThis;
function Constr() {
// 保存構造函數中的this
savedThis = this;
}
// 通過new關鍵字執(zhí)行構造函數
var inst = new Constr();
// 構造函數中的this指向的就是新創(chuàng)建的對象實例inst
console.log(savedThis === inst); // true
如果你沒有用new關鍵字去執(zhí)行構造函數,那么就要分析函數被調用時所屬的作用域了
function Point(x, y) {
this.x = x;
this.y = y;
}
var p = Point(7, 5); // 沒有用new關鍵字去執(zhí)行構造函數!
console.log(p === undefined); // 沒有用new,所以構造函數沒有返回一個實例對象, 所以p === undefined
// 沒有用new關鍵字,Point(7,5);就只是把函數執(zhí)行了一遍
// ()左邊是Point,屬于全局對象,所以this指向全局對象
console.log(x); // 7
console.log(y); // 5
在事件處理器(event handler)中this的指向
<div id="test">I am an element with id #test</div>
function doAlert() {
alert(this.innerHTML);
}
doAlert(); // undefined
// doAlert()屬于全局對象
var myElem = document.getElementById('test');
myElem.onclick = doAlert;
alert(myElem.onclick === doAlert); // true
myElem.onclick(); // I am an element
// ()左邊是onclick也就是doAlert,屬于myElem,所以this指向myElem
那個元素觸發(fā)事件,this就指向那個元素
總結
以上,對于函數中的this,通過查看()左邊所屬的對象去確定,真的很好用。
而實質上,this是在創(chuàng)建函數的執(zhí)行環(huán)境時,在創(chuàng)建階段確定的,因此,弄透執(zhí)行環(huán)境,去思考執(zhí)行環(huán)境創(chuàng)建階段的this的指向,this的指向就不會弄錯了吧。