I once thought that in the world of JavaScript, all methods are public and I cannot truly define a private method technically. Today I discovered again: Actually, I was wrong!
Copy the codeThe code is as follows:
var Person = function(name,sex){
= name;
= sex;
var _privateVariable = "";//Private variables
//The method defined in the constructor is a private method
function privateMethod(){
_privateVariable = "private value";
alert("Private method is called! Private member value: " + _privateVariable);
}
privateMethod(); //Private methods can be called inside the constructor
}
= function(){
alert("name: " + + ", gender: " + );
}
var p = new Person("Yang Guo under the Bodhi Tree","Male");
();
//();// An error will be reported here, and the private method cannot be called by the instance
alert(p._privateVariable);//Show: undefined
Description: The function defined in the constructor of a class is a private method; and the variable declared in the constructor is also equivalent to a private variable. (However, it is different from the concept of private membership in strongly typed languages like C#, such as it cannot be called in other methods other than non-constructors)
Similarly, we can also implement encapsulation similar to set and get attributes
Copy the codeThe code is as follows:
var Person = function(){
var salary = 0.0;
= function(value){
salary = value;
}
= function(){
return salary;
}
}
var p = new Person();
(1000);
alert(());//Return 1000
alert();//Return undefined
Note: The concepts of "variable scope", "function call context (this), "closure", and "prototype chain" in js are indeed worthwhile to understand. These hurdles have been crossed, and I believe that the level of JS novices (such as ours) will also be lowered to a new level.