在 JavaScript 中将 canvas 设为全局对象是一个好习惯吗?

发布于 2024-10-16 18:43:15 字数 207 浏览 1 评论 0原文

我正在尝试用 JavaScript 构建一个利用 HTML5 的 canvas 标签的项目。但是,由于在我的对象/原型中引用范围,我遇到了一些问题。

将画布元素(无论其中有多少个恰好是)全局化是一个好主意(或者更确切地说,好的实践)吗?由于想要坚持 OOP 心态,我一直试图尽可能避免创建全局变量,但我没有找到解决此问题的更好解决方案。

如有任何反馈,我们将不胜感激。

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'm not finding many better solutions to this issue.

Any feedback is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

匿名。 2024-10-23 18:43:15

实际上,用变量/引用破坏全局对象永远不是一个好主意。几乎在所有情况下它都是可以避免的。

您提到您正在遵循“OOP 心态”,这使得情况变得更糟。在这种情况下,你的设计理念显然做错了。回到绘图板!

正如我多次提到的,避免这种情况的最小努力是创建一个函数上下文,它代表代码的范围。

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

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');
}());
蓝梦月影 2024-10-23 18:43:15

您的主要问题似乎是将信息传递到事件(不接收参数的函数)中。

解决这个问题的方法是闭包。函数可以使用在其作用域中定义的任何变量,您可以利用这一点来发挥自己的优势。

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);

您可以通过传递“画布管理器”对象来使事情变得更复杂,以允许在运行时更改画布以及添加您可能需要的其他变量......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文