Jump to content

Organizing JavaScript by setting scope?


onetrickwolf
 Share

Recommended Posts

I come from Flash and was able to something like this (it's been awhile so syntax likely incorrect):

//This...house1 = new Object();house1.living_room.chair = new Chair();house1.living_room.chair2 = new Chair();//...could be shortened to something like this:house1 = new Object();house1.living_room {chair = new Chair();chair2 = new Chair();}

Is there an equivalent in JavaScript?  It just makes the code a bit easier to read when creating complicating objects that I can't easily convert in to some type of constructor.  Been searching forever can't find anything.

Link to comment
Share on other sites

In JavaScript, you could just do this:

var house1 = {    living_room: {        chair: new Chair(),        chair2: new Chair()    }};

Although your example raises the question why you don't just use an array if you have more than one thing of the same "type", as is the case with your chairs:

var house1 = {    living_room: {        chairs: [new Chair(), new Chair()]    }}
Link to comment
Share on other sites

Is there an equivalent in JavaScript?

 

I think you're looking for JavaScript's "with" statement. However, use of "with" is strongly discouraged and the statement is now deprecated. Instead, I normally reduce repeated use of a long reference as follows:

var lr = house1.livingRoom;lr.chair1 = new Chair();lr.chair2 = new Chair();
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...