简体   繁体   中英

I don't understand the Scope

1 - why when I run the below code I got undefind instead "a=1" ?

function f1(){a=1; f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

like this example the resualt is "a=1" .

function f1(){a=1; f2();}
function f2(){alert(a);}
var a= 5;
f1();

With

a = f1();

you are assigning the result of calling f1 to a . Yet, f1 does not return anything, it evaluates to undefined . You'd need to use a return statement:

function f1(){a=1; return f2(); }

Btw, this is not a scope problem. You don't have any variables that are local to your functions, everything accesses the same a .

You probably forget a return statement to get your a value

function f1(){a=1; return f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

f1 does not return anything that's why try the below

function f1(){a=1; return f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

even if does not make lots of sense

您需要从f1显式返回。

第一个例子中的函数f1没有返回任何值,所以这就是原因

During the line a = f1(); the f1 function isn't returning anything so a is getting set to undefined.

I'm not positive what you are trying to do; if you add more I could make a suggestion for how to make it do what you want.

f1() doesn't return any value. Returning nothing is the same as returning undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM