Javascript Object Question
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 开发者_JAVA技巧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.
It's actually just bad code. MeetingPage.colors = new Object();
is setting a property called colors
on the MeetingPage
function, i.e:
function MeetingPage(){ }
MeetingPage.colors = {};
Which is perfectly valid since all functions in JavaScript are objects. The problem is that if you have multiple instances of meeting page:
var meeting1 = new MeetingPage();
var meeting2 = new MeetingPage();
The code you posted will reset colors
. It should either should be written as this.colors = {}
, or it should be set outside of the function as in my first snippet.
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
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.
精彩评论