Of private method is defined in javascript
- 2020-03-30 01:34:27
- OfStack
I used to think that in the javascript world, all methods are public and you can't really technically define a private method.
var Person = function(name,sex){
this.name = name;
this.sex = sex;
var _privateVariable = "";//Private variable & NBSP;
//Methods defined in the constructor are private methods
function privateMethod(){
_privateVariable = "private value";
alert(" Private method called! Private member value: " + _privateVariable);
}
privateMethod(); //A private method & NBSP 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();// An error will be reported and private methods will not be invoked by the instance
alert(p._privateVariable);//Display: undefined
Class constructor defined in the function, is a private method; Variables declared with var in constructors are also private variables. (however, there are differences between this and the notion of private members in strongly typed languages like c#, such as not being able to be called in methods other than constructors.)
Similarly, we can also implement the encapsulation of properties like set and get
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());//Back to 1000
alert(p.salary);//Returns the undefined
Note: the concepts of "variable scope "," function call context (this)"," closure ", and" prototype chain "in js are all worth a bit of work.