JavaScript creates examples of private functions and variables

Source: Internet
Author: User


They firmly believe that if you create a Property object, or create a three-dimensional global variable, this is a fair game for anyone. However, with some very simple patterns, you can use JavaScript to protect the privacy of accessing a given object or variable!

Classes

You may know that there is no real class in JavaScript, but using features and prototypes, we can simulate very well. Using this pattern, you can also simulate private variables:

Function myclass (parameter)  {    // create the private var     var privatevar = 8,         self

 = this;     self.parameter = parameter     // function that  handles the private     function handleprivate ()  {  

      return privateVar ? privateVar-- :  false;     }     // public method that calls the  handler     // returns parameter until it ' s been  Accessed 8 times     this.getprivate ()  {      

  return handleprivate ()  ? self.parameter : null;  &nbsP; &NBSP}} 

Private creation is accessed by building functions, and only by building functions, by adding special access methods to access private properties, in which the value is accessed only through a specific method.

Closures

The pattern closes around a variable range, returning an object or function to access the variable. This is a simple example:

var accessor =  (function ()  {    //  create the private var     var privateVar =  "you 
Can ' t see me,  ';          // some other functionality here that
 periodically changes privatevar, because it has access to it     // [ MORE CODE HERE&NBSP]        
  // return the accessor     return function (name)  {
        return privateVar + name;
    };
})();
 use!  currentvalue = accessor ("David");   "You can ' T see me, david" 

Privatevar variables cannot be closed externally, so there is no way to access them directly. We do this, however, to be able to change back from the closure there is a definition function. Therefore, the variable remains private and you can access its value, but not direct access. You can also return a method to modify a protected object variable:

var accessor = (function () {

//The "private"

var val = 9;

//An object for getting and setting return

{

get:function () {return

val *        3;

},

set:function (s) {

val = s;

}

};

}) ();

Of course, the above pattern allows users to regain a similar approach:

accessor = function (n) {return "My custom string," + N;}

Usually all the features that handle private information are closed, preventing users from rewriting the method's problem. Something like this:

var accessor =  (function ()  {         var 

permissions = {};          function handleresult (Perm)  {         // do something with the result     

}          return function (permissiontocheck, callback)  {         if (Permissions[permissiontocheck])  != undefined)  {            callback (permissions[

Permissiontocheck]);

        }         else {             $.post ({                 url:  " /permissions "                 data: {                     perm: permissiontocheck                  }             &NBSP}). Success (function (res)  {            

    callback (Handleresult (res));

            });

        }     };     }) ();

In JavaScript simplicity must be beautiful, do not write it down because it does not provide the same explicit structure for other languages

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.