function var1() {
consol开发者_JS百科e.log("in function one");
var varval1 = "life";
alert("var one value"+varval1);
return varval1;
}
function var2() {
console.log("in function two");
alert("var two value"+varval1);
}
var1();
var2();
I want to access the value of varval1
inside var2()
. However, it gives an error saying the value is not defined.
Thanks
How about
function var1(){
console.log("in function one");
var varval1 = "life";
alert("var one value"+varval1);
return varval1;
}
function var2( varval1 ){
console.log("in function two");
alert("var two value"+varval1);
}
var2(var1());
varval1
is defined in the scope of the function var1
but not in var2
's scope. So, it won't be available to the code outside var1
. However, all the functions defined inside var1
will have access to the variables defined inside it.
You have several options here.
- Define function
var2
insidevar1
. (but then, you won't be able to callvar2
easily usingvar2()
) - Declare
varval1
as a global variable. (By removing var in front of it. But, this is generally a bad idea) 3) - Return the value of
varval1
from functionvar1
and store it in a variableval2
can access.
Also, try to name your variables and functions meaningfully.
Scope: http://en.wikipedia.org/wiki/Scope_%28programming%29
Changing the line where varval1
is defined will do it:
function var1() {
console.log("in function one");
varval1 = "life";
alert("var one value"+varval1);
return varval1;
}
This is also equivalent to writing
window.varval1 = "life";
Change you var2()
to
function var2(){
console.log("in function two");
varval1=var1();
alert("var two value"+varval1);
}
精彩评论