2013-04-25 48 views
0

我會盡力在我的問題上儘可能清楚如此:JavaScript閉包上下文的其他屬性會發生什麼?

有很多博客和教程可以解釋閉包,但是我無法弄清楚的是上下文的其他屬性會發生什麼從哪個封閉創建? jsFiddle

function func(){ 

    this.context_field = "context_field"; 
    this.context_method = function(){ 
     console.log("context method"); 
    }; 


    func = function(param, change){ 
     if(typeof(change) === 'undefined'){ 
      //...... 
      console.log(param + " " + context_field + " from original func - closure\n\n"); 
      //..... 
    } 
    return func; 
}; 

func()("Init finished and call"); 
func("Call again", ""); 
+2

您是否明白'this'是'window'(假設非嚴格模式)? – apsillers 2013-04-25 19:15:10

回答

2

在這個例子中沒有創建的上下文,這是因爲關鍵詞「這個」在函數內部「FUNC」指的是窗口(全局對象)。

創建上下文聲明瓦爾這樣的:

var context_field = "context_field"; 
var context_method = function(){ 
    console.log("context method"); 
}; 
+0

所以context_field和context_method保持私有,只能在該上下文中使用,除非我明確地在內部匿名函數中替換'func'返回context_method [updated_code](http://jsfiddle.net/bogdan_vq/Uea6G/ 1 /) – 2013-04-25 19:43:51

+0

在我的第一個變體中,我知道,有一個上下文,但是窗口上下文或我可能是錯的? – 2013-04-25 19:47:00

0

所以從中創建封閉的上下文的其他屬性是活的,可以被稱爲封閉,而是讓他們唯一可用的途徑內外面正在返回他們。

function func(){ 

    var context_field = "context_field"; 
    var context_method = function(){ 
     console.log("context method lives on"); 
    }; 

    func = function(param){ 
     console.log(param + " func and " + context_field); 
     return context_method; 
    } 
    return func; 
}; 

func()("Init finished and call"); 
func("Call again")(); 
相關問題