开发者

How to pass access the variable of one function in another function

开发者 https://www.devze.com 2023-01-31 21:45 出处:网络
function var1() { consol开发者_JS百科e.log(\"in function one\"); var varval1 = \"life\"; alert(\"var one value\"+varval1);
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.

  1. Define function var2 inside var1. (but then, you won't be able to call var2 easily using var2())
  2. Declare varval1 as a global variable. (By removing var in front of it. But, this is generally a bad idea) 3)
  3. Return the value of varval1 from function var1 and store it in a variable val2 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消