First, let's look at the common functions of javascript.
Copy codeThe Code is 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
It can be seen that the external interface must interact with the function sum. It can only be called and returned, but cannot access the parameters c and internal functions add (). This is a normal logic for functions.
Next, let's look at the class usage of javascript.
Copy codeThe Code is 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. );
Here, the sum object t is created through new. Using t, you can call the show method to display the parameters and, or directly retrieve the parameter information.
Use both methods to generate private variables and methods.
Copy codeThe Code is as follows:
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 ();
From this example, we can see that variables and Methods declared by var cannot be called externally, but external variables can interact with private variables through public methods as a bridge.
Suggestion: To facilitate reading and differentiation, add one or two underscores before the private variables and methods.