在javascript
中揭示了匿名函數包裝的目的,通常會遇到一個特殊的練習,其中整個.js文件都封裝在匿名函數中,例如(function(function){...} {){...})(){)()()()()()()。儘管這似乎令人困惑,但該技術具有特定的優勢,尤其是用於命名和控制函數和變量的可見性。
理解動機
函數outerfunction(){
函數nirnfunction(){
//內部功能具有私人可見性
}
}
在這種情況下,外部功能是可以在全球範圍內訪問的,但是interfunction是私人的。
namespacing and私有成員
var myplugin =(function(){
var private_var;
功能private_function(){
//私人功能
}
返回 {
public_function1:function(){
//公共功能
},,
public_function2:function(){
//公共功能
}
};
})();
In this case, private_var and private_function are private within the myPlugin namespace, but public_function1 and public_function2 can be accessed from outside the wrapper.
function outerFunction() {
function innerFunction() {
// Inner function with private visibility
}
}
Function Arguments in the Self-Invocation
The final parentheses when self-invoking the function allow for passing of arguments.例如,當創建jQuery插件時,開發人員會通過jQuery或$:
[function(jq){...代碼...})(jquery);
本地重新定義global parameter在本地重新定義績效效益,並提供績效效益,並提供績效效益,並促進壓縮。 JavaScript是實現隱私,命名空間組織和改進性能的一種手段。它們提供了一種將代碼封裝在文件中的方便方法,從而可以創建可重複使用的組件和庫。