因此,您在選項1之後。
// Option 1: Object in a gloabl scrope
var myObject = {
myFunction: function(){
alert('I am here');
}
};
(function ($) {
// Option 2: Object in a function scope
var myObject2 = {
myFunction2: function(){
alert('I am here 2');
}
};
$(document).ready(function() {
// Option 3: Object in a local (to the "(function ($) {") function scope
var myObject3 = {
myFunction3: function(){
alert('I am here 3');
}
};
//alerts 'I am here 2';
myObject2.myFunction2();
//alerts 'I am here 3';
myObject3.myFunction3();
});
//alerts 'I am here 2';
myObject2.myFunction2();
//Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
myObject3.myFunction3();
}(jQuery));
//alerts 'I am here';
myObject.myFunction();
//Uncaught TypeError: myObject2.myFunction2 is not a function - can't access a locally scoped function on a global scope
myObject2.myFunction2();
//Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
myObject3.myFunction3();
只有在文檔準備好後,MyObject變量纔會被初始化。你爲什麼想在此之前稱呼它? –
你想要哪個物體可用?只在範圍(文件)中聲明?或者也在外部範圍(文件)? – lshettyl