At one time, I thought that in the javascript world, all methods are public and cannot be technically defined as a private method. Today I found again that I was wrong!
Copy codeThe Code is as follows:
Var Person = function (name, sex ){
This. name = name;
This. sex = sex;
Var _ privateVariable = ""; // Private variable
// The methods defined in the constructor are private methods.
Function privateMethod (){
_ PrivateVariable = "private value ";
Alert ("Private method called! Private member value: "+ _ privateVariable );
}
PrivateMethod (); // The constructor can call private methods internally.
}
Person. prototype. sayHello = function (){
Alert ("name:" + this. name + ", Gender:" + this. sex );
}
Var p = new Person ("Yang Guo under the bodhi tree", "male ");
P. sayHello ();
// P. privateMethod (); // an error is reported here. The private method cannot be called by the instance.
Alert (p. _ privateVariable); // display: undefined
Note: The function defined in the constructor of the class is a private method. The variable declared by using var in the constructor is also equivalent to a private variable. (However, the concept of private members in strong-type languages such as c # is different, for example, they cannot be called in methods other than constructors)
Similarly, we can implement encapsulation similar to the set and get attributes.
Copy codeThe 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 (); // returns 1000
Alert (p. salary); // return undefined
Note: In js, the concepts of "variable scope", "function call context (this)", "closure", and "prototype chain" are indeed worth some time to understand, these barriers have crossed, and the level of js beginners (such as the stream of my generation) is expected to reach a new level.