2015-10-20 63 views
2

我有以下邏輯:參考的IIFE內部功能

var first_function = (function(d3, second_function) { 
    function third_function(param1, param2) { 
    /* do stuff here */ 
    } 
})(d3, second_function); 

外的IIFE結構,訪問第三個功能,我可以正常做這樣的事情:

first_function.third_function(data1, data2); 

我在哪裏我錯了?

+2

請注意,IIFE不會返回任何東西,並立即執行,所以基本上'first_function'是'undefined'? – adeneo

+1

你的IIFE返回了什麼?您需要返回一個具有third_function屬性的對象,否則您將無法訪問它。 –

+1

另外,您不能訪問IIFE之外的'third_function',這就是閉包的作用,內部函數在外部範圍中不可用,除非您返回某些內容以使其可用。真正的問題變成了;爲什麼你會使用IIFE? – adeneo

回答

2

它沒有返回它,所以函數只是蒸發。你可以做這樣的事情:

var first_function = (function(d3, second_function) { 
    function third_function(param1, param2) { 
    /* do stuff here */ 
    } 
    return third_function; 
})(d3, second_function); 

然後,你可以這樣訪問:如果你想從IIFE訪問屬性

first_function(paramForThirdFunc1,paramForThirdFunc2); 
+0

嘗試此操作。將盡快報告。 – daveycroqet

+0

@daveycroqet我犯了一個錯誤,再次檢查這個:) –

+0

它的工作,謝謝。 – daveycroqet

5

,你需要做的是財產可通過返回一個對象

var first_function = (function(d3, second_function) { 

    // this function is unavailable to the outer scope 
    function third_function(param1, param2) { 
    /* do stuff here */ 
    } 

    // this object allows us to access part of the inner scope 
    // by passing us a reference 
    return { 
    third_function: third_function 
    } 
}})(d3, second_function); 

有趣的是,我們還可以利用這個來創建'私有'方法和變量。

var first_function = (function(d3, second_function) { 

    // this function is unavailable to the outer scope 
    function third_function(param1, param2) { 
    /* do stuff here */ 
    } 

    var myPrivate = 0; // outer scope cannot access 

    // this object allows us to access part of the inner scope 
    // by passing us a reference 
    return { 
    third_function: third_function, 
    getter: function() { 
     return myPrivate; // now it can, through the getter 
    } 
    } 
}})(d3, second_function); 

如果您想了解更多關於這是如何工作的,我建議您閱讀JavaScript範圍和關閉。

+0

是的,這是他想要的。 –

+0

我希望我能給你兩個答案。 Harshal只是更快,雖然這是一個更加充實的答案,我爲此感謝你。 – daveycroqet

+2

他們只是假的互聯網點;) –