2013-02-21 56 views
0

(對不起,我的英語= /) 我在'onload'時創建一個數組。javascript:公共數組與對象

(這一點:

var $ = { 
    ratio: 0.7, 
    screen: 500, 
    margin: 10, 
    canvas: document.getElementById("canvas"), 
    ctx: document.getElementById("canvas").getContext("2d"), 
} 

$.canvas$.ctx是給「空」 這個工作,如果我把它改寫

... 
canvas: function(){return document.getElementById("canvas")} 
... 

,但如果我想打電話給這個變量看起來是這樣的。 $ .canvas () 我該如何使這個變量沒有'()'?

+1

似乎畫布未加載的[爲什麼jQuery的或DOM方法如\'的getElementById \'找不到元件?](http://stackoverflow.com/questions還 – karaxuna 2013-02-21 17:23:52

+1

可能重複/ 14028959/why-does-jquery-or-a-dom-method-such-getelementbyid-not-find-the-element) – 2013-02-21 17:34:13

回答

1

看起來它與您的$變量的作用域的問題。通過在window.onload函數中聲明var關鍵字,其範圍是本地函數而不是全局範圍。

你可以把它定義在onload函數,而不是外面:

var $; // in the global scope 

window.onload = function(){ 
    $ = { 
     ratio: 0.7, 
     screen: 500, 
     margin: 10, 
     canvas: document.getElementById("canvas"), 
     ctx: document.getElementById("canvas").getContext("2d") 
    }; 

    console.log($.canvas); 
    console.log($.ctx); 
}; 

通過在全球範圍內宣佈,它可以在onload功能的外部訪問。

Fiddle

+1

我不認爲這是一個範圍問題。 OP說,如果他將一個函數賦值給'$ .canvas',它就可以工作。如果這是一個範圍問題,那麼這個錯誤就像'Can not read property'canvas'of undefined'。 – 2013-02-21 17:35:31

2

試試這個:

window.onload = function(){ 
    window.$ = { 
     ratio: 0.7, 
     screen: 500, 
     margin: 10, 
     canvas: document.getElementById("canvas"), 
     ctx: document.getElementById("canvas").getContext("2d"), 
    } 
}