const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
console.log(shape.diameter());
console.log(shape.perimeter());
I know the diameter is 20, but why perimeter shows NaN?
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
console.log(shape.diameter());
console.log(shape.perimeter());
I know the diameter is 20, but why perimeter shows NaN?
This is a scope issue - the radius variable is not available inside the perimeter method and so is undefined. Changing the function to a regular method resolves the issue.
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter() {
return 2 * Math.PI * this.radius
}
};
console.log(shape.diameter()); //gives 20
console.log(shape.perimeter()); // gives 62.83185307179586
() => ...), the scope of this is the same scope as where the function is defined. In this case, it is window.Depending on how you plan to use it, you may be better served with a class. In the example below, this in the arrow function refers to the Circle instance.
class Circle {
constructor(radius) {
this.radius = radius;
}
diameter() {
return this.radius * 2;
}
perimeter = () => 2 * Math.PI * this.radius;
}
const shape = new Circle(10);
console.log(shape.diameter());
console.log(shape.perimeter());
That said, if you are using a class, I prefer the way that diameter is defined over perimeter as an arrow function.