Let’s first look at the common function usage of javascript
function sum(a, b){
var c = 10;
function add(){
c ;
}
add();
return a b c;
}
var d = sum(4,5);
alert(d) // 20
It can be seen that external interaction with function sum can only be done through calls and return values, and cannot be accessed The parameter c and the internal function add() are inside. This is normal logic for functions.
Let’s look at the usage of JavaScript classes
function sum (pa,pb) {
this.a = pa;
this.b = pb;
this.show = function(){
alert(this.a this.b);
}
}
var t = new sum(4,5);
t.show();
alert(t.a);
Created here via new The object t of sum is obtained. Through t, you can call the show method to display the parameter sum, or you can directly get the parameter information
Combining the two methods will produce the effect of private variables and methods.
function sum(pa,pb) {
var __c = 10; //Private variable
function __addc(){ //Private method
__c;
}
this.a = pa; //Public variable
this. b = pb; //Public variable
this.setc = function(pc){ //Public method
__c = pc;
__addc();
}
this.show = function (){ //Public method
alert(this.a this.b __c);
}
}
var t = new sum(4,5);
t.setc( 1);
t.show();
As can be seen from this example, variables and methods declared by var cannot be called externally, but externally can use public methods to implement bridges with private variables Interactive
Suggestion: To facilitate reading and distinction, add one or two underscores before naming private variables and methods.