Improving the encapsulation of code in JavaScript

Source: Internet
Author: User

One of my interview questions is to ask how to avoid page reference JS, function, variable repetition, conflict.

On the big side, JavaScript should be introduced in modular development, in line with the AMD specification;

From the small aspect, it is probably the scope of the limited variables and functions, which also involves a little thunderclap piercing concept of closure.

As we all know, JavaScript has no classes, only functions. In fact, its function is similar to the class, functions can be defined inside the function. For. NET, this is not supported until the recent c#7.

So, we can define functions and variables in a function so that it is isolated from the outside:

 <head ;  </head ;  <body ;  </body ;  </html ;  <script ;   (function   ()  { function  f1   ()  {};    var  v1; ....}) (); </script ;    

Writing in a page like this is equivalent to:

<html><head></head><body></body></html><script>    function f1(){};    var v1;    ....</script>

But encapsulation is a lot better, avoid the latter of this tile straightforward, the methods and variables completely exposed to the outside world. And (function(){})(); This approach can be applied to sub-functions, and even to all functions, layers of encapsulation, no end. And there is a closure attribute that does not have to worry about global binding access to the inner layer of the function:

(function(){    function f1(){}    function f2(){}    $("#btn1").click(function(){        f1();        f2();    });}

Improve the encapsulation of code in JavaScript

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.