Details about how to create a privileged method_javascript in js private scopes

Source: Internet
Author: User
This article mainly introduces in detail how to create a privileged method in the js private scope. What is a privileged method? The privileged method is a public method that has the right to access private variables and private functions, if you are interested, you can refer to the examples in this article to share the creation of privileged methods in the js private scope for your reference. The specific content is as follows:

Privileged MethodsIs the public method that has the right to access private variables and private functions:

function MyObject(){  var privateVariable = 10;  function privateFunction(){    return false;  }  this.publicMethod = function(){    privateVariable ++;    return privateFunction();  };}  var x = new MyObject();console.log(x.publicMethod()) ;//false

Private variables and functions are defined in the private scope. You can also create privileged methods, such:

(Function () {var privateValue = 10; function privateFunction () {return false;} MyObject = function () {}; // No var is a global variable, in strict mode, MyObject is reported. prototype. publicMethod = function () {privateValue ++; return privateFunction () ;}}) (); var instance = new MyObject (); console. log (instance. publicMethod ());

Here we can see that a global build function is defined in the private scope. One of the methods is to return a private variable and attribute in the private scope. Write it as follows to better understand:

Obj = function(){};(function(){  var x = 10;  function y(){    return x + 10;  }  Obj.prototype.say = function(){    console.log(y());  };})()var ins = new Obj();ins.say();

The above is all the content of this article, hoping to help you learn.

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.