Examples of advanced usage methods for JavaScript closures

Source: Internet
Author: User
This article presents an example of the advanced usage method for JavaScript closures, with the need for friends to refer to

Extended
Code:

Copy Code code as follows:


var blogmodule = (function (my) {


My. Addphoto = function () {


//Add internal code


 };


return to my;


} (Blogmodule));


Say:
It passes itself into the method, and then implements the extension of the method, sort of like part assembly.
Code:

Copy Code code as follows:


var blogmodule = (function (me) {var oldaddphotomethod = My. Addphoto;


My. Addphoto = function () {//overloaded method, still able to invoke old side} via Oldaddphotomethod; return to my;} (Blogmodule));


Say:
The advantage is that you can call the previous method.
Cloning and inheritance
Code:

Copy Code code as follows:


var Blogmodule = (function (old) {var i = {}, key; for (key) {if (Old.hasownproperty (key)) {My[key] = Old[key]; } var Oldaddphotomethod = old. Addphoto; My. Addphoto = function () {//After cloning, the rewrite, of course, you can continue to invoke Oldaddphotomethod}; return to my; } (Blogmodule));


Say:
A simple cloning implementation
Share private objects across files
Code:

Copy Code code 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 to my; } (Blogmodule | | {}));


Say:
Blogmodule._seal () lock, _unseal () unlock, to achieve the privatization of internal variables. I don't think it's the best way to do this, but we can learn the lock-locked function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.