在 JavaScript 中将 canvas 设为全局对象是一个好习惯吗?
我正在尝试用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,用变量/引用破坏全局对象永远不是一个好主意。几乎在所有情况下它都是可以避免的。
您提到您正在遵循“OOP 心态”,这使得情况变得更糟。在这种情况下,你的设计理念显然做错了。回到绘图板!
正如我多次提到的,避免这种情况的最小努力是创建一个函数上下文,它代表代码的范围。
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.您的主要问题似乎是将信息传递到事件(不接收参数的函数)中。
解决这个问题的方法是闭包。函数可以使用在其作用域中定义的任何变量,您可以利用这一点来发挥自己的优势。
您可以通过传递“画布管理器”对象来使事情变得更复杂,以允许在运行时更改画布以及添加您可能需要的其他变量......
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.
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...