At one time, in the world of JavaScript, all methods were publicly owned, and they could not really define a private method from technical. Today I discovered again: Actually, I am wrong!
Copy code code as follows:
var Person = Function (name, sex) {
this.Name = name;
this.sex = sex;
var _privatevariable = ""; // Private variables
// The method defined in the constructor is a private method
function privatemedhod () {
_privatevariable = "Private Value";
alert ("Private method is called! Private member value:" + _privatevariable);
}
Privatemethod (); // The private method can be called inside the constructor
}
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 /) ;// The error will be reported here. The private method cannot be called by instances
alert (p._privatevariable); // Show: undefined
Note: The function defined in the constructor of the class is a private method; the variables declared using VAR in the constructor are also equivalent to private variables. (However, there are still differences in the concept of private members in strong types such as C#such as C#.
Similarly, we can also realize the packaging of similar set, get attributes
Copy code code 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.Setsalarly (1000);
alert (p.getsalar ()); // Return 1000
alert (p.salary); // Return to undefined
Note: "Variable Scope" in JS, "function calling context (this)", "closure", "prototype chain" are indeed worth spending some efforts to understand, these hurdles have across the past, js novice players (For example, the flow of my generation), I believe it will be a new level.