Tim Shedor
Tim Shedor

Reputation: 165

Reuse a property value as a variable within the same object

I'm sorry if my vocab is misleading in the question, but essentially I want to use a variable as the value of a property within one javascript object. For example:

var fruits = {
    banana: 'yellow',
    apple: 'red',
    jazz_apple: apple
}

If I define a function and call this, I can access the value no problem, i.e.

var fruits = {
    banana: 'yellow',
    apple: 'red',
    jazz_apple: function() {
        return this.apple //fruits.jazz_apple() returns 'red'
    }
}

But I don't want to define a function to get this value. Is there a way to reuse the previously declared color for fruits.apple ('red') on the new property fruits.jazz_apple within the object without a function?

Upvotes: 4

Views: 2973

Answers (2)

Steven Wexler
Steven Wexler

Reputation: 17279

You need to use functions to have access to this (aka context). I recommend creating a fruits function. You can also think of the fruits function as a class because classes are functions in Javascript.

function fruits() {
    this.banana = 'yellow';
    this.apple = 'red';
    this.jazz_apple = this.apple;
}

var myFruits = new fruits();
myFruits.jazz_apple;

If you don't want to create a fruits class, you can also used variables scoped to the object.

function () {
    var apple = 'red',
        fruits = {
            banana: 'yellow',
            apple: apple,
            jazz_apple: apple
        };
}

Upvotes: 2

jacobangel
jacobangel

Reputation: 6996

I don't think there is a good way to do what you're doing without using a previously defined value, because fruits hasn't finished being created by the time you're trying to reference it.

The only reason the function above works is because you're running it after fruits has finished being initialized.

Your best bet is adding the property after initilizing, or reusing a declared variable:

var fruits = {
    banana: 'yellow',
    apple: 'red'
};

fruits.jazz_apple = fruits.apple;

or

var apple_color = 'red';

var fruits = {
  banana: 'yellow',
  apple: apple_color,
  jazz_apple: apple_color
}

Upvotes: 0

Related Questions