[英]I don't understand the Scope
1 - why when I run the below code I got undefind instead "a=1" ? 1 - 为什么当我运行下面的代码时,我得到了unfind而不是“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" . 像这个例子,resualt是“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
. 您将调用f1
的结果分配给a
。 Yet, f1
does not return anything, it evaluates to undefined
. 然而, f1
没有返回任何东西,它评估为undefined
。 You'd need to use a return
statement: 您需要使用return
语句:
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
. 你没有函数本地的任何变量,一切都访问相同的a
。
You probably forget a return statement to get your a value 你可能忘记了一个return语句来获取你的值
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 f1
没有返回任何原因,为什么尝试以下
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(); 在行a = f1()期间; the f1 function isn't returning anything so a is getting set to undefined. f1函数没有返回任何内容,所以a被设置为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. f1()
不返回任何值。 Returning nothing is the same as returning undefined. 返回任何内容与返回undefined相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.