2014-10-10 92 views
0

我有这个myObject在foo.js中进行了decalred,并在bar.js中进行了修改。带getScript的jQuery全局变量

我试图在getScript完成时得到结果。然而,如果在jQuery中对其进行decalred,似乎myObject不是全局变量。

有人可以向我解释这个吗?

foo.js

/* 
    // this works fine, but I want to decalre it inside jQuery 
    var myObject = { 
     str: "hello world", 
     num: "123" 
    }; 
*/ 

$(function() { 

    // this makes myObject NOT a global valriable 
    var myObject = { 
     str: "hello world", 
     num: "123" 
    }; 

    alert(myObject.str + " " + myObject.num); 

    $.getScript("bar.js", function() { 
     alert(myObject.str + " " + myObject.num); 
    }); 
}); 

bar.js

$(function() { 
    myObject = { 
     str: "new string", 
     num: "999" 
    }; 
}); 

回答

0

OK,感谢阿伦,但这个工程...... window .myObject

$(function() { 

    // global variable defined inside function 
    window.myObject = { 
     str: "hello world", 
     num: "123" 
    }; 

    // ... 
}); 
+0

是一样宣布它外面 – 2014-10-10 06:17:08

+0

@ArunPJohny是它们具有相同的范围,而我在我的问题说......我希望变量是**在** jQuery中声明。 – user1643156 2014-10-10 06:30:06

0

既然你声明的函数里面的变量,它是局部的功能。你可以做的是外面声明变量,但分配jQuery的准备处理程序中的价值

foo.js

/* 
    // this works fine, but I want to decalre it inside jQuery 
    var myObject = { 
     str: "hello world", 
     num: "123" 
    }; 
*/ 

var myObject; 
$(function() { 

    // this makes myObject NOT a global valriable 
    myObject = { 
     str: "hello world", 
     num: "123" 
    }; 

    alert(myObject.str + " " + myObject.num); 

    $.getScript("bar.js", function() { 
     alert(myObject.str + " " + myObject.num); 
    }); 
}); 

bar.js

$(function() { 
    myObject = { 
     str: "new string", 
     num: "999" 
    }; 
}); 

演示: Plunker

+0

所以...(在我的例子,从2个js文件)的2个jQuery函数中的变量不是在相同的范围内,是对? – user1643156 2014-10-10 06:03:58

+0

@ user1643156是...取决于变量的声明方式 – 2014-10-10 06:13:01