1

Im starting to work more and more with Javascript and I occasinally run into the following problem.
I want to assign values, based on values I just entered.

Simple example:

var Example = {
    valueA : 100,
    valueB : 20,
    valueC : Example.valueA / Example.valueB
}

But this gives Example is undefined at the valueC line. I'm assuming that the Example object isn't ready to be used at this point, it first has to "finish being made".

I could do:

var Example = {
    valueA : 100,
    valueB : 20,
    valueC : -1 // Gets value later
}
Example.valueC = Example.valueA / Example.valueB

In this example this would be perfectly accaptable, but I end up in situations where I would have a lot of these "post init" problems, or the assigned values are a bit more complecated (eg a formulae).

Can something like "Simple Example" work? My Current solution feels like overkill, I need something more elegant which reads better when reading the code.

Martijn
  • 15,791
  • 4
  • 36
  • 68

1 Answers1

1

You could use a getter:

The get syntax binds an object property to a function that will be called when that property is looked up.

An advantage is, you can assign other values to property valueA or valueB and get the actual result of the division.

var Example = {
    valueA: 100,
    valueB: 20,
    get valueC() { 
        return this.valueA / this.valueB;
    }
};

document.write(Example.valueC);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • But this would make `valueC` a function? This will be a variable I'll call often, wouldn't that be a bit intens? – Martijn Apr 15 '16 at 11:26
  • yes, it's a function, but it the call works without parenthesis and it acts like a variable with a value. don't worry about the calling. – Nina Scholz Apr 15 '16 at 11:28