var statement
declare a variable.
var variable1 [= value1] [, variable2 [= value2], ...]
Parameters
Variable, variable2
The name of the variable being declared.
Value, value2
The initialization value assigned to the variable.
Description
Use the VAR statement to declare a variable. These variables can be assigned in the script after declaration or declaration
A question about the Var variable
A friend asked a JS problem, a paragraph can not see any problems in the code, ie under the error: "Object doesn ' t support this property or method."
The code is as follows |
Copy Code |
function foo (obj) { Producttree = Obj.tostring (); document.getElementById (' Producttree '). InnerHTML = Producttree; }
|
At the beginning, also think that the error refers to the ToString method of obj, around a half a day detour, no fruit.
Later, notice that the variable name is producttree without the Var declaration, plus getElementById (' Producttree ') indicates that there is an element with an ID of Producttree, And we know that in IE you can get a reference to the DOM element directly by ID, so~
So ah, local variables must be declared with Var, not only because the Var will become a global variable, but also because of IE, there may be such a very inexplicable error ....
var variable instance 1
The code is as follows |
Copy Code |
function Test () { VAR1 = 2; alert (VAR1); } Test (); alert (VAR1); This can be displayed as 2 function Test () { var var1 = 2; alert (VAR1); } Test (); alert (VAR1);
|
No error is defined for the variable
Instance 2
We can also use this to illustrate local variables
This is used inside the function, and it always points to the object that calls him, and see the example below to see
The code is as follows |
Copy Code |
var test={ A: "Test", Msg:function () { A= "1234"; alert (THIS.A); var msg1= function () { alert (THIS.A); } MSG1 (); } } Test.msg (); This will show "test", "1234" respectively. |
Attention:
As with algebra, a JavaScript variable is used to hold a value or an expression.
You can give a variable a short name, such as X, or a more descriptive name, such as length.
JavaScript variables can also hold text values, such as Carname= "Volvo."
Rules for JavaScript variable names:
variables are case-sensitive (Y and y are two different variables)
variables must start with a letter or underscore
Note: Because JavaScript is case sensitive, variable names are case sensitive