开发者

Is it good practice to make canvas a global object in JavaScript?

I'm trying to build a project in JavaScript that utilizes HTML5's canvas tag. However, I'm running into a few issues due to referencing scopes in my objects/prototypes.

Is it a good idea (or rather, good practice) to just make the canvas element (however many of them there happen to be) global? I've been trying to avoid making global variables whenever possible, due to wanting to stick to an OOP-mentality, but I'开发者_如何学Pythonm not finding many better solutions to this issue.

Any feedback is appreciated.


It's actually never a good idea to clobber the global object with variables / references. It's avoidable in almost all situations.

You mentioned you're following an "OOP-mentality" which makes it even more worse. In this case, you obviously did something very wrong in your design concept. Back to the drawingboard!

As I mentioned many times, a minimum effort to avoid this is to create a Function context, which represents the scope if your code.

(function() {
    // all of your code
    var canvas = document.getElementById('mycanvas');
}());


Your main problem seems to be passing information into events (functions that don't receive parameters).

The solution to this is closures. Functions can use any variables defined in their scope and you can use this to your advantage.

function make_event_handler(canvas){
    function my_event_handler(){
        alert('look, I can use '+canvas);
    }
    return my_event_handler;
}

elem.onclick = make_event_handler(canvas);

You can make this more complicated by say, passing a "canvas manager" object instead to allow changing canvases at runtime as well as add other variables you might need...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜