4

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?

2 Answers 2

2

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
        };
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.