sawa
sawa

Reputation: 168081

How to define a property based on another property

I want to define a property to some namespace depending on another property. The following is my attempt to assign someNameSpace.x2 based on someNameSpace.x1:

someNameSpace = {
  x1: 100,
  x2: x1 * 0.5,
};

but it fails. What is the correct way to do this?

Upvotes: 2

Views: 172

Answers (6)

user1726343
user1726343

Reputation:

someNameSpace = {
  x1: 100,
  get x2(){return this.x1 * 0.5},
};
someNameSpace.x2; // 50
someNameSpace.x1 = 5;
someNameSpace.x2; // 2.5

Use a getter instead of cheating like all these other fools. The value of property x2 is now truly dependent on the value of x1 :P

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77966

You can't do that because x1 hasn't been defined yet in the scope.

someNameSpace = { x1 : 100 };
someNameSpace.x2 = someNameSpace.x1 * 0.5;

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120178

You could define a function that returns the value

var NS = {
  x1: 100,
  computeX2: function(){
     return this.x1 * 0.5;
  }
}

Some javascript frameworks like ember.js allow you define so-called "computed properties" this way.

Upvotes: 0

AndyPerlitch
AndyPerlitch

Reputation: 4729

You can do this:

someNameSpace = {
    x1: 100
}
someNameSpace.x2 = x1 * 0.5;

Upvotes: 0

Joe
Joe

Reputation: 82594

You can't reference the object in the object literal defining itself.

var something = { x: 3 }; 
something.x2 = something.x * 2;

You can declare it; then add whatever properties you want after the declaration.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71908

Here is a trick using a self-executing function:

var someNameSpace = (function(){
    var x1 = 100;
    return {
        x1: x1,
        x2: x1 * 0.5
    };
})();

http://jsfiddle.net/T2kyZ/

Upvotes: 0

Related Questions