Home  >  Article  >  Web Front-end  >  Basics of getting started with javascript - private variables_javascript skills

Basics of getting started with javascript - private variables_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:34:041069browse

Let’s first look at the common function usage of javascript

Copy the code The 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 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
Copy the code The 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.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.

Copy code The 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();

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn