First look at the usage of ordinary functions in 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 if the external one wants to interact with the function sum, it can only be called and returned, and the parameter c and internal function add() cannot be accessed. This is normal logic for functions.
Next, let’s look at the usage of javascript
function sum(pa,pb) {
= pa;
= pb;
= function(){
alert( + );
}
}
var t = new sum(4,5);
();
alert();
Here, the sum object t is created through new. Through t, you can call the method show to display the parameters and parameters, or you can directly obtain parameter information
Combining 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++;
}
= pa; //Public variables
= pb; //Public variables
= function(pc){ //Public method
__c = pc;
__addc();
}
= function(){ //Public method
alert( + + __c);
}
}
var t = new sum(4,5);
(1);
();
From this example, we can see that the external cannot call the variables and methods declared by var, but the external can interact with the private variables through public methods for bridge implementation.
Suggestion: For easy reading and distinction, private variables and methods are underlined before naming.
Copy the 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 if the external one wants to interact with the function sum, it can only be called and returned, and the parameter c and internal function add() cannot be accessed. This is normal logic for functions.
Next, let’s look at the usage of javascript
Copy the codeThe code is as follows:
function sum(pa,pb) {
= pa;
= pb;
= function(){
alert( + );
}
}
var t = new sum(4,5);
();
alert();
Here, the sum object t is created through new. Through t, you can call the method show to display the parameters and parameters, or you can directly obtain parameter information
Combining two methods will produce the effect of private variables and methods.
Copy the codeThe code is as follows:
function sum(pa,pb) {
var __c = 10; //Private variable
function __addc(){ //Private method
__c++;
}
= pa; //Public variables
= pb; //Public variables
= function(pc){ //Public method
__c = pc;
__addc();
}
= function(){ //Public method
alert( + + __c);
}
}
var t = new sum(4,5);
(1);
();
From this example, we can see that the external cannot call the variables and methods declared by var, but the external can interact with the private variables through public methods for bridge implementation.
Suggestion: For easy reading and distinction, private variables and methods are underlined before naming.