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.