Home  >  Article  >  Web Front-end  >  Description of defining private methods in javascript (private method)_javascript skills

Description of defining private methods in javascript (private method)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:02:141145browse

I once thought that in the world of JavaScript, all methods are public, and it is impossible to technically define a private method. Today I discovered again: In fact, I was wrong!

Copy code The code is as follows:

var Person = function(name,sex){
this.name = name;
this. sex = gender; ;
      alert("Private method is called! Private member value: " _privateVariable);                                                                                                                                                                                Person.prototype.sayHello = function(){
alert("Name: " this.name ", gender: " this.sex);
}

var p = new Person("Bodhi Yang Guo under the tree","male");   
p.sayHello();

//p.privateMethod();//An error will be reported here, and the private method cannot be called by the instance
alert(p._privateVariable);//Display: undefined


Explanation: The function defined in the constructor of the class is a private method; and the variables declared with var in the constructor are also equivalent So private variables. (However, it is different from the concept of private members in strongly typed languages ​​such as C#. For example, it cannot be called in methods other than non-constructors)

Similarly, we can also implement encapsulation of properties like set and get




Copy code

The code is as follows:


var Person = function(){  var salary = 0.0; this.setSalary = function(value){  salary = value; }
this.getSalary = function(){
return salary;
}
}

var p = new Person();

p.setSalary(1000) ;
alert(p.getSalary());//Return 1000
alert(p.salary);//Return undefined


Note: "Variable scope" in js , "Function call context (this)", "closure", and "prototype chain" are indeed worth spending some time to understand. After these hurdles have been overcome, I believe that the level of JS novices (such as myself) It will also reach a new level.
Statement:
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