Home  >  Article  >  Web Front-end  >  Examples of advanced usage of javascript closures_javascript skills

Examples of advanced usage of javascript closures_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:29:581185browse

Extension
Code:

Copy code The code is as follows:

var blogModule = (function ( my) {
my.AddPhoto = function () {
//Add internal code
};
return my;
}(blogModule));

Say:
Pass itself into the method, and then implement the expansion of the method, which is a bit like assembling parts
Code:
Copy code The code is as follows:

var blogModule = (function (my) {var oldAddPhotoMethod = my.AddPhoto;
my.AddPhoto = function () { // Overloaded method, The old method can still be called through oldAddPhotoMethod}; return my;}(blogModule));

Say:
The advantage is that you can call the previous method.
Clone and inheritance
Code:
Copy code The code is as follows:

var blogModule = (function (old) { var my = {}, key; for (key in old) { if (old.hasOwnProperty(key)) { my[key] = old[key]; } } var oldAddPhotoMethod = old. AddPhoto; my.AddPhoto = function () { // After cloning, it has been rewritten. Of course, you can continue to call oldAddPhotoMethod }; return my; } (blogModule));

Say:
Simple cloning implementation
Share private objects across files
Code:
Copy code The code is as follows:

var blogModule = (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; }; return my; } (blogModule || {}));

Say:
blogModule._seal() locks and _unseal() unlocks to privatize internal variables. I think this implementation is not the best, but we can learn this unlocking and locking function.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn