This article introduces the examples of advanced use of javascript closures. If you have any need, refer to the extension.
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 extension of the method, a bit like assembling parts.
Code:
The Code is as follows:
Var blogModule = (function (my) {var oldAddPhotoMethod = my. AddPhoto;
My. AddPhoto = function () {// overload method, you can still use oldAddPhotoMethod to call the old party}; return my;} (blogModule ));
Say:
The advantage is that you can call the previous method.
Cloning and inheritance
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 is overwritten. Of course, you can continue to call oldAddPhotoMethod}; return my;} (blogModule ));
Say:
Simple clone implementation
Private object sharing across files
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 () locks to private internal variables. I think this implementation is not the best, but we can learn this locking function.