標籤:
在函數內部有兩個特殊對象:arguments和this,this的指向其實是非常靈活的,它會根據調用function的對象不同,導致了this的指向不同。當在全域範圍下調用函數時,this指向window。例如:
| 12345678 |
window.color = ‘red‘;var o = {color: ‘blue‘};function sayColor(){ alert(this.color);}sayColor(); //‘red‘o.sayColor = sayColor;o.sayColor(); //‘blue‘ |
我們知道this對象在執行時是基於函數的執行環境綁定的:當函數被作為某個對象的方法調用時,this指向那個對象。但匿名函數的執行環境具 有全域性,所以this指向window。但在閉包中,這一點可能不太明顯。先說一下閉包吧,我的理解是在一個函數內部建立另一個函數,而內建函式可以訪 問外部函數範圍中的變數,這是因為內建函式的範圍鏈中包含外部函數的範圍。
var name = ‘the window‘;var object = { name: ‘My object‘, getFunc: function (){ return function(){ return this.name; } }};alert(object.getFunc()()); //‘the window‘
看到這裡,大家可能會驚訝,為什麼this指向的是全域範圍。因為內建函式在搜尋this和arguments時,只會搜尋到其使用中的物件,永遠不可能直接存取外部函數中的這兩個變數。
為了讓閉包內的this能訪問到外部範圍中的變數,我們可以在定義匿名函數之前把this附一個值,當定義閉包後就可以訪問外部變數了。因為它是我們在外部函數(包含函數)中特意聲明的一個變數。
| 1234567891011 |
var name = ‘the window‘;var object = { name: ‘My object‘, getFunc: function (){ var that = this; return function(){ return that.name; } }};alert(object.getFunc()()); //‘My object‘ |
this對象的擷取取決於上下文;函數什麼時候調用才決定了this到底引用的啥。
也可以參考這篇部落格: http://www.cnblogs.com/linfangshuhellowored/p/4248540.html
js中this的用法