1

Is there any way to assign an object property like pear below? (example doesn't work)

var fruitColors = { apple: "green", pear: fruitColors.apple};

I can achieve it by doing this however, but I'd like to do it like above if it's possible.

var fruitColors = { apple: "green" };
fruitColors.pear = fruitColors.apple;

2 Answers 2

1

I don't think you can - as the fruitColors object doesn't exist at the time you are trying to access it's property.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't do it during initialization. You could make a constructor if you wanted, but not sure if it would be worth it.

function FruitColors() {
    this.apple = "green";
    this.pear = this.apple;
}

var fruitColors = new FruitColors;

or in newer implementations, you could use the get syntax to make pear reference apple:

var fruitColors = { 
    apple: "green",
    get pear() { return this.apple; }
}

but this isn't widely supported across browsers if that's your target.

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.