Home >Web Front-end >JS Tutorial >JavaScript private variables and public variables
Variables in javascript include private variables and public variables, also called local variables and global variables. This article uses example code to illustrate their differences
Look at code 1 first:
function car(){
var wheel = 3; //Declare a private variable
this.wheel = 4;//Declare a public variable
alert(wheel);
alert(this.wheel);
}
var car1 = new car();
The result is: 3 4
Code 2:
function car(){
var wheel = 3;//Declare a private variable
this.wheel = 4;//Declare a public variable
}
var car1 = new car();
alert(car1.wheel); Result: 4
var wheel = 3 is a local variable, this.wheel=4 is a public variable. If you want to access the private variables in car, please see Code 3:
function car(){
var wheel = 3;//Declare a private variable
this.wheel = 4;//Declare a public variable
this.getPrivateVal = function(){
return wheel;
}
}
var car1 = new car();
alert(car1.getPrivateVal());
Result: 3
When writing javascript, everyone should pay more attention to the scope of variables. Otherwise, there will be some questions that are difficult to find answers to.
The above is the content of JavaScript private variables and public variables. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!