2013-02-21 41 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"), 
    } 
}