首页 > 代码库 > js深度模块模式

js深度模块模式

本文摘自http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

1 Anonymous Closures

(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());

2Global Import

(function ($, YAHOO) {
// now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));


3Module Export

var MODULE = (function () {
var my = {},
privateVariable = 1;

function privateMethod() {
// ...
}

my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};

return my;
}());

 

高级模式
1 Augmentation
var MODULE = (function (my) {
my.anotherMethod = function () {
// added method...
};

return my;
}(MODULE));

2 Loose Augmentation

var MODULE = (function (my) {
// add capabilities...

return my;
}(MODULE || {}));


3Tight Augmentation

var MODULE = (function (my) {
var old_moduleMethod = my.moduleMethod;

my.moduleMethod = function () {
// method override, has access to old through old_moduleMethod...
};

return my;
}(MODULE));

4 Cloning and Inheritance
var MODULE_TWO = (function (old) {
var my = {},
key;

for (key in old) {
if (old.hasOwnProperty(key)) {
my[key] = old[key];
}
}

var super_moduleMethod = old.moduleMethod;
my.moduleMethod = function () {
// override method on the clone, access to super through super_moduleMethod
};

return my;
}(MODULE));

5 Cross-File Private State
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 || {}));

6Sub-modules
MODULE.sub = (function () {
var my = {};
// ...

return my;
}());

7Conclusions
var UTIL = (function (parent, $) {
var my = parent.ajax = parent.ajax || {};

my.get = function (url, params, callback) {
// ok, so I‘m cheating a bit :)
return $.getJSON(url, params, callback);
};

// etc...

return parent;
}(UTIL || {}, jQuery));

 

js深度模块模式