0

In code below I'm creating a circle objects and giving it's keys some values. I'm setting the radius property of the circle object to it's diameter divided by 2. When we console.log it's value, it returns NAN. How to fix this problem?

let circle = { posX: 40, posY: 70, diameter: 30, radius: this.diameter/2 } console.log(circle.radius) 
2
  • 1
    this does not refer to circle. You could call circle.radius = circle.diameter/2 after the initial assignment or add it as a function to the object. Commented Jul 26, 2021 at 13:57
  • 1
    May I ask why you are setting both the radius and the diameter attributes, when you can easily calculate one from the other if/when you need it? Commented Jul 26, 2021 at 14:01

2 Answers 2

2

You need a method inside the object in order to do it, because you are using the this keyword, and it needs a function to work:

let circle = { posX: 40, posY: 70, diameter: 30, radius: function () { return this.diameter/2; } } console.log(circle.radius())

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

Comments

0

You can use a class:

class Circle { posX; posY; diameter; radius; constructor(posX, posY, diameter){ this.posX = posX; this.posY = posY; this.diameter = diameter; this.radius = diameter / 2; } } 

Then when you instanciate it like the following, the radius is automatically set to diameter/2

let circle = new Circle(40, 70, 30); // circle.radius is 15 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.