-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?

CSnerd
  • 2,129
  • 8
  • 22
  • 45

3 Answers3

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().

soktinpk
  • 3,778
  • 2
  • 22
  • 33
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);
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
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
Community
  • 1
  • 1
mc01
  • 3,750
  • 19
  • 24