带getScript的jQuery全局变量

时间:2014-10-10 05:52:25

标签: jquery global-variables getscript

我在foo.js中对此myObject进行了decalred,并在bar.js中进行了修改。

我试着在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"
    };
});

2 个答案:

答案 0 :(得分:1)

由于您在函数内声明了变量,因此它是函数的本地变量。你可以做的是在外面声明变量,但是在jQuery ready handler

中分配值

<强> 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

答案 1 :(得分:0)

好的,谢谢Arun,但这很有效...... window。myObject

$(function() {

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

    // ...
});