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!
VaR person = function (name, sex) {This. name = Name; this. sex = sex; VaR _ privatevariable = ""; // Private variable // the method defined in the constructor, that is, the private method 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.
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 the 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.