First look at the common function usage of javascript
Copy Code code as follows:
function sum (a,b) {
var C = 10;
function Add () {
C + +;
}
Add ();
Return a + B + C;
}
var d = sum (4,5);
Alert (d)//20
As you can see, external to interact with the sum of functions, only through the invocation and return value form, you cannot access the inside parameter C and internal function add (). This is normal logic for a function.
Next look at the class usage of JavaScript
Copy Code code as follows:
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);
Here, the object T of Sum is created by new. You can call method show through T to display parameters and, or you can take parameter information directly
The combination of two methods produces the effects of private variables and methods.
Copy Code code as follows:
function sum (PA,PB) {
var __c = 10; Private variable
function __ADDC () {//Private method
__c++;
}
THIS.A = PA; Public variables
this.b = PB; Public variables
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, the variables and methods of VAR declaration cannot be invoked externally, but the external can interact with private variables through public method for the bridge.
Recommendation: For readability and distinction, private variables and methods add one or two underscores before naming.