Gunther
Gunther

Reputation: 2645

Using properties inside a Javascript object literal

I'm looking to create javascript json object that has a dynamic field that will just return a value based on previously specified properties. So far This is what I have...

var car = {
  color: 'red',
  wheels: 4,
  hubcaps: 'spinning',
  age: 4,
  full_name: this.color + ' ' + this.spinning
}

I was wondering if this is possible to do? My goal is to be able to reference values such as car.color or car.full_name. For this example car.full_name would return the value red spinning

Upvotes: 1

Views: 79

Answers (2)

Jay Harris
Jay Harris

Reputation: 4271

You can wrap your object in a function so you can perform operations on it, e.g. concatenations.

var car = function () {
    var color     = 'red',
        hubcaps   = 'spinning',
        full_name = color + ' ' + hubcaps;

    return {
       color: color,
       wheels: 4,
       hubcaps: hubcaps,
       age: 4,
       full_name: full_name
    };
// (); <- calls the anonymous function after defining it
}();

// true
car.full_name === "red spinning";

Edit: Like what @Jimmyt1988 said, if you want to instantiate new versions of this functions, i.e. OO Javascript, you can remove the inline function call (); and use it like so

var myCar = new car();

alert(mycar.color);

Upvotes: 3

jfriend00
jfriend00

Reputation: 707328

You cannot refer to other fields in the javascript literal when it is statically declared like you are doing because in the eyes of the parser, the object does not yet exist (it hasn't finished parsing) and it also doesn't set the this ptr like you are trying to use either.

Instead, you would have to do this:

var car = {
  color: 'red',
  wheels: 4,
  hubcaps: 'spinning',
  age: 4,
}

car.full_name = car.color + ' ' + car.spinning;

Your other option would be to turn full_name into either a function or a getter so that it is computed dynamically based on the other field values.

If you want full_name to always be dynamic, then you probably want to use a getter which can have a function behind it, but can be used like a property.

Upvotes: 0

Related Questions