-1

I want to access the variable in the object, something like below:

var menuSetup = { m : [100,200], height: m[0], // m is not defined } var menuSetup = { m : [100,200], height: this.m[0], // I tried this, still failed } 

So can I access the variable in the object?

8
  • You can't, that's about it. Commented Jul 17, 2014 at 18:45
  • You can't do that unfortunately... Commented Jul 17, 2014 at 18:45
  • You could define a variable outside of the object and use that in both places. jsfiddle.net/5taBt Commented Jul 17, 2014 at 18:49
  • 1
    Why would you want to do this? It would cause cluttering. What you really want here is an object with a method height() that returned the value you want. Commented Jul 17, 2014 at 18:52
  • @Casey Falk this is just an example Commented Jul 17, 2014 at 19:03

3 Answers 3

0

Unfortunately, you can't do that. This is because the properties of menuSetup haven't been defined yet. For example,

var menuSetup = { m: [100, 200], height: menuSetup.m[0] }; 

will through (in chrome) TypeError: Cannot read property 'm' of undefined because menuSetup is just undefined (because it was hoisted by the var declaration)

The only two ways I can think of is to

a) Save m as a variable before. For example:

var m = [100, 200]; var menuSetup = { m: m, height: m[0] } 

b) Use a method instead of a variable and execute it.

var menuSetup = { m: [100, 200], height: function() { return this.m[0]; } } 

Then, when you get menuSetup.height, you would actually do menuSetup.height().

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this:

var MenuSetup = function() { this.m = [100,200]; this.height = this.m[0]; } var menuSetup = new MenuSetup(); console.log(MenuSetup.height); 

3 Comments

I always get beat out by about 15 seconds :P
Shouldn't the constructor start with a capital letter and the instance start with the lower i.e. var menuSetup = new MenuSetup()?
@soktinpk good point, I was keeping OP casing but you're right this is different and merit changing.
0

Not the way you're doing it. In JavaScript you cannot reference another property while creating the same object, because the object doesn't yet exist until after the closing } at the end.

You could use a constructor function instead though, as explained in answers to this similar question.

function MenuSetup() { this.m = [100, 200]; this.height = this.m[0]; } var menu = new MenuSetup(); console.log(menu.height) //100 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.