2014-10-10 30 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