aqib
aqib

Reputation: 3

How to assign a property in object to the value of some property in same object in javascript?

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)

Upvotes: 0

Views: 60

Answers (2)

AlexSp3
AlexSp3

Reputation: 2293

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())

Upvotes: 2

Sleepwalker
Sleepwalker

Reputation: 863

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

Upvotes: 0

Related Questions