Advanced usage of javascript closures _ javascript skills

Source: Internet
Author: User
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.
Related Article

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.