Home > Article > Web Front-end > Detailed explanation of creating privileged methods in js private scope_javascript skills
The example in this article shares the method of creating privileges in the js private scope for your reference. The specific content is as follows
Privileged methods are public methods that have access to 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, and privileged methods can also be created, such as:
(function(){ var privateValue = 10; function privateFunction(){ return false; } MyObject = function(){}; //没有var 属于全局变量,严格模式下会报错 MyObject.prototype.publicMethod = function(){ privateValue ++; return privateFunction(); }; })(); var instance = new MyObject(); console.log(instance.publicMethod());
Here you can see that a global constructor function is actually defined in the private scope; one of the methods is to return a private variable and property in the private scope. You can understand it better by writing it like this:
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 the entire content of this article, I hope it will be helpful to everyone’s study.