2012-07-27 74 views
0

我有一个全局变量a,我在函数内部使用它并为它赋值。当我在函数外使用这个变量时,它给了我undefined函数内部的JavaScript全局变量定义

例如:

var a; 
function my_func(){ 
    a=5; 
} 
console.log(a); //outputs undefined, how do I get the value 5 here 

为什么我得到undefined,而不是5


它的力量解决了我的问题。

var id; 

function set_id(myid){ 
id=myid; 
} 

function get_id(){ 
return id; 
} 

$("#btn").click(function(){ 
$.post("....", function(data){ //data reurns a JSON 
    set_id(id); //success!! 
} 
} 

$("#show").click(function()[ 
console.log(get_id()); //doesn't work, how do I get this workin.. Where am I going wrong 
} 
+0

安慰变量之前,你需要调用的函数,my_func,并将();直到那么var a将是未定义的。 – Shreedhar 2012-07-27 18:46:48

回答

3

你应该调用函数my_func日志前:

var a; 
function my_func(){ 
    a=5; 
} 
my_func();  //<-- here 
console.log(a); 
0
var a; 

function my_function1() { 
    return 5; 
} 

function my_function2() { 
    a = 5; 
} 

/* Either of these options below will work to change the value of "a" to 5*/ 

// a = my_function1() 
// my_function2()​​​