About JS Creating a privileged method in a private scope _javascript tips

Source: Internet
Author: User

This article shares the JS private scope of the creation of privileged methods for your reference, the specific contents are as follows

A privileged method is a public method that has access to private variables and private functions:

function MyObject () {
  var privatevariable = ten;
  function Privatefunction () {return
    false;
  }
  This.publicmethod = function () {
    privatevariable + +;
    return privatefunction ();}
  ;
}  
var x = new MyObject ();
Console.log (X.publicmethod ());//false

Private scopes can also create privileged methods, such as:

(function () {
  var privatevalue = ten;
  function Privatefunction () {return
    false;
  }
  
  MyObject = function () {}; No var belongs to the global variable, the strict mode will error
  
  MyObject.prototype.publicMethod = function () {
    privatevalue + +;
    return privatefunction ();
  };
}) ();

var instance = new MyObject ();
Console.log (Instance.publicmethod ());

Here you can see that in fact, a global constructor is defined in the private scope, one of which is to return a private variable and property in a private scope. Write the following so you can better understand:

OBJ = function () {};

(function () {
  var x = ten;
  function y () {return
    x +;
  }

  Obj.prototype.say = function () {
    console.log (y ());
  };
}) ()

var ins = new Obj ();
Ins.say ();

The above is the entire content of this article, I hope to help you learn.

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.