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!
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:
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.