Home > Web Front-end > JS Tutorial > body text

Detailed explanation of creating privileged methods in js private scope_javascript skills

WBOY
Release: 2016-05-16 15:18:33
Original
1368 people have browsed it

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
Copy after login

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());

Copy after login

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();
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template