導(dǎo)言
在這篇文章中我們將討論一個(gè)與執(zhí)行上下文直接相關(guān)各更多細(xì)節(jié)。討論的主題就是this關(guān)鍵字。
實(shí)踐表明,這個(gè)主題很難,在不同執(zhí)行上下文中this值的確定經(jīng)常導(dǎo)致問(wèn)題。
許多程序員習(xí)慣的認(rèn)為,在程序語(yǔ)言中,this關(guān)鍵字與面向?qū)ο蟮某绦蚓o密相關(guān),完全指向通過(guò)構(gòu)造器創(chuàng)建的新的對(duì)象。在ECMAScript中也是這樣執(zhí)行的,但正如你看到的那樣,這并不限于創(chuàng)建對(duì)象的定義。
讓我們更詳細(xì)的了解ECMAScript中真正的this值是什么?
定義
這個(gè)值是執(zhí)行上下文中的一個(gè)屬性。
activeExecutionContext = { VO: {...}, this: thisValue};
這里VO使我們前面討論的變量對(duì)象。
this與上下文中可執(zhí)行代碼密切直接相關(guān),這個(gè)值取決于進(jìn)入的上下文,代碼在上下文中運(yùn)行時(shí)一成不變
全局代碼中的this值
在這里一切都簡(jiǎn)單。在全局代碼中,this始終是全局對(duì)象本身,這樣有可能間接的引用它。
// explicit property definition of// the global objectthis.a = 10; // global.a = 10alert(a); // 10// implicit definition via assigning// to unqualified identifierb = 20;alert(this.b); // 20// also implicit via variable declaration// because variable object of the global context// is the global object itselfvar c = 30;alert(this.c); // 30
函數(shù)代碼中的this值
在函數(shù)代碼中使用this 時(shí)很有趣,這種情況很難且會(huì)導(dǎo)致很多問(wèn)題。
這種類型的代碼中,this值的首要特點(diǎn)(或許是最主要的)是它不是靜態(tài)的綁定到一個(gè)函數(shù)。
正如我們上面曾提到的那樣,這個(gè)值取決于進(jìn)入的上下文,在一個(gè)函數(shù)代碼中,這個(gè)值在每一次完全不同。
但是,在代碼運(yùn)行時(shí)的this值是不變的,也就是說(shuō),既然它不是一個(gè)變量,就不可能為其分配一個(gè)新值(相反,在Python編程語(yǔ)言中,它明確的定義為對(duì)象本身,在運(yùn)行期間可以不斷改變)。
var foo = {x: 10};var bar = { x: 20, test: function () { alert(this === bar); // true alert(this.x); // 20 this = foo; // error alert(this.x); // if there wasn't an error then 20, not 10 }};// on entering the context this value is// determined as "bar" object; why so - will// be discussed below in detailbar.test(); // true, 20foo.test = bar.test;// however here this value will now refer// to "foo" – even though we're calling the same functionfoo.test(); // false, 10