简体   繁体   English

javascript全局变量在函数内部未定义

[英]javascript global variable undefined inside function sometime

For some reason a JavaScript global variable becomes undefined inside function when set to local variable sometime. 由于某些原因,有时将JavaScript全局变量设置为局部变量时,该变量在函数内部变得不确定。 For example, in below sample the local often become " undefined ". 例如,在下面的示例中, local经常变为“ undefined ”。 Could anyone of you please advise? 你们中有人可以建议吗?

I'm expecting the value of " local " is "global value" in functionB() and functionC() or doStringProcessingA() and doStringProcessingB() . 我期望在functionB()functionC()doStringProcessingA()doStringProcessingB() ,“ local ”的值是“ global value”。 The value of " local " is " undefined ". local ”的值是“ undefined ”。 I'm sure there's no other places assign value or set undefined to global in anywhere. 我确定没有其他地方可以在任何地方分配值或将undefined设置为global。

I've checked below links, but it seems not related. 我检查了下面的链接,但似乎无关。 'Hoisted' JavaScript Variables and Why a variable defined global is undefined? “悬挂式” JavaScript变量以及为什么未定义全局变量?

functionA() was called by onClick event from HTML. HTML中的onClick事件调用了functionA()。

 var global;

 function functionA(){
    global = "global value";
 }

 function functionB(){
    var local = global;     
    doStringProcessingA(local);
 }

 function functionC(){
    var local = global;     
    doStringProcessingB(local);
 }

<div onclick="functionA()">
    <span class="Text">Submit</span>
</div>

Can you try this 你可以试试这个吗

Var global = "text";
function  functA{
     Var lol = global; 
     dostringprocess(local);
  }

I think in your code it taking local variable from FunctioA, and also you can check in two ways 我认为在您的代码中它采用了FunctioA的局部变量,并且您也可以通过两种方式进行检查

1) open console and see the log what error it showing exactly by putting some log message in every function in function stack 1)打开控制台,并通过在函数堆栈的每个函数中放置一些日志消息来查看日志确切显示了什么错误

2) you can use closure 2)可以使用闭包

since your global value is defined under a functionA() so when you call a function B() or functionC() directly your global variable does not contain any value.. so for this you have to intialise the value of global variable.. 因为您的全局值是在functionA()下定义的,所以当您直接调用函数B()或functionC()时,您的全局变量不包含任何值..为此,您必须初始化全局变量的值。

var global="Earth";                      // now it will not give any errror

 function functionA(){
    global = "global value";
 }

 function functionB(){
    var local = global;     
    doStringProcessingA(local);
 }

 function functionC(){
    var local = global;     
    doStringProcessingB(local);
 }

<div onclick="functionA()">
    <span class="Text">Submit</span>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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