我在这里读到了“跨文件私有状态” http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html 任何人都可以解释我这段代码???
var MODULE = (function (my) {
var _private = my._private = my._private || {},
_seal = my._seal = my._seal || function () {
delete my._private;
delete my._seal;
delete my._unseal;
},
_unseal = my._unseal = my._unseal || function () {
my._private = _private;
my._seal = _seal;
my._unseal = _unseal;
};
// permanent access to _private, _seal, and _unseal
return my;}(MODULE || {}));
感谢!!!
答案 0 :(得分:0)
不确定您是否想要了解跨文件私有状态或特定代码段,但了解模块模式取决于您对闭包有多了解。由于js中没有访问说明符,但可以通过使用闭包来实现。应用程序可以包含大量的js文件,并且每个文件都可以公开方法或函数或变量,并且可以同时使任何变量,方法或函数私有。
档案A.js
var a= (function(){
function _init(){
_someOtherFunction();
}
function _someOtherFunction(){ //private function only accessible in a module
// Some code goes here
}
return{
init:_init
}
}(a || {}))
a只是暴露了它的init函数,但不是_someOtherFunction()可用。
文件B.js 定义b并调用A.js公开的函数init
var b = (function(){
a.init(); // a.init has been exposed
a._someOtherFunction // Code breaks here since _someOtherFunction is unexposed
}(b ||{})
希望它能帮助您理解跨文件私有状态