JavaScript 对象问题
我是 Javascript 的初学者。我正在查看其他人编写的以下代码:
function MeetingPage()
{
MeetingPage.colors = new Object();
}
...
var meeting = new MeetingPage();
根据我所看到的,我相信 MeetingPage 函数创建了一个对象,稍后有人在会议中保留该对象。什么是 MeetingPage.colors? MeetingPage 前缀是某种全局前缀吗?它是某种“this”指针吗?
任何建议将不胜感激。
I'm a beginner w/ Javascript. I'm looking at the following code that someone else wrote:
function MeetingPage()
{
MeetingPage.colors = new Object();
}
...
var meeting = new MeetingPage();
From what I've seen, I believe that the MeetingPage function creates an object that later someone holds onto in meeting. What is the MeetingPage.colors? Is the MeetingPage prefix some kind of global? Is it a "this" pointer of some kind?
Any suggestions would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这实际上只是糟糕的代码。
MeetingPage.colors = new Object();
在MeetingPage
function 上设置一个名为colors
的属性,即:这是完全有效的,因为 JavaScript 中的所有函数都是对象。问题是,如果您有多个会议页面实例:
您发布的代码将重置
颜色
。它应该写为this.colors = {}
,或者应该设置在函数的外部,如我的第一个代码段中所示。It's actually just bad code.
MeetingPage.colors = new Object();
is setting a property calledcolors
on theMeetingPage
function, i.e:Which is perfectly valid since all functions in JavaScript are objects. The problem is that if you have multiple instances of meeting page:
The code you posted will reset
colors
. It should either should be written asthis.colors = {}
, or it should be set outside of the function as in my first snippet.当我了解 javascript 中的不同对象模式时,这次演讲确实很有帮助。示例代码包含在第二个链接中(视频介绍了它)。
http://alexsexton.com/?p=94
http://alexsexton.com/inheritance/demo/
http://alexsexton.com/?p=51
当然,你也应该阅读 http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742
HTH
This talk was really helpful when I got into different object patterns in javascript. Example code is included in the second link (the video introduces it).
http://alexsexton.com/?p=94
http://alexsexton.com/inheritance/demo/
http://alexsexton.com/?p=51
Of course, you should also definitely read http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742
HTH
这是创建类属性的 JavaScript 语法。请注意,它是一个类属性,而不是实例属性,这意味着它在该类的所有实例之间共享。 (如果您了解 C++,这就像类静态)但是,我认为将类属性放入构造函数本身是无效的。我认为每次创建新的 MeetingPage 时,颜色类属性都会被清除。
This is the JavaScript syntax for creating Class Properties. Note, it is a class property not an instance property, that means it is shared across all instances of the class. (If you know C++ this is like a class static) However, I didn't think it was valid to put a class property inside the constructor itself. I would think that every time a new MeetingPage is created the colors class property will get wiped out.