Once thought in the JavaScript world, all methods are public, can not really technically define a private method, today again found: I was wrong!
Copy Code code as follows:
var person = function (name,sex) {
THIS.name = name;
This.sex = sex;
var _privatevariable = "";//Private variable
The method defined in the constructor, that is, a private method
function Privatemethod () {
_privatevariable = "Private Value";
Alert ("Private method is called!") Private member Value: "+ _privatevariable";
}
Privatemethod (); Private methods can be invoked inside the constructor
}
Person.prototype.sayHello = function () {
Alert ("Name:" + this.name + ", Sex:" + this.sex);
}
var p = new Person ("Yang over" under the banyan Tree, "male");
P.sayhello ();
P.privatemethod ()//here will be an error, private method cannot be called by the instance
alert (p._privatevariable);//display: undefined
Description: A function defined in a class's constructor is a private method, whereas a variable declared in a constructor with Var is also a private variable. (However, the notion of private members in a strongly typed language like C # is different, such as not being invoked in a method other than a constructor)
Similarly, we can implement a package similar to the Set,get property
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.setsalary (1000);
Alert (P.getsalary ());//Return 1000
alert (p.salary);/return undefined
Note: "Variable scope" in JS, "function call context (this)," closure "," prototype chain "These concepts are indeed worth a little time to understand, these lines across the past, JS novice (such as the flow of our own) level of confidence will also be small a new level.