SoFunction
Updated on 2025-04-06

Detailed explanation of creating privileged methods in js private scope

This article shares the method of creating privileges in the private scope of js for your reference. The specific content is as follows

Privileged MethodsIt is a public method that has permission to access private variables and private functions:

function MyObject(){
  var privateVariable = 10;
  function privateFunction(){
    return false;
  }
   = function(){
    privateVariable ++;
    return privateFunction();
  };
}  
var x = new MyObject();
(()) ;//false

Defining private variables and functions in a private scope, you can also create privileged methods, such as:

(function(){
  var privateValue = 10;
  function privateFunction(){
    return false;
  }
  
  MyObject = function(){}; //No var is a global variable, and an error will be reported in strict mode.  
   = function(){
    privateValue ++;
    return privateFunction();
  };
})();

var instance = new MyObject();
(());

It can be seen here that in fact, a global constructor is defined in the private scope; one of the methods is to return a private variable and attribute in the private scope. Written as follows to get a better understanding:

Obj = function(){};

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

   = function(){
    (y());
  };
})()

var ins = new Obj();
();

The above is all about this article, I hope it will be helpful to everyone's learning.