0

I don't know why perimeter and area property is Nan ?? can anyone explain this to me??

function Rectangle(a, b) {
    return {
        length:a,
        width:b,
        perimeter: 2 * (this.length + this.width),
        area: this.length * this.width,
        print(){
            console.log(this.perimeter);
            console.log(this.area);
        }
    };
}

const rect = Rectangle(10, 20);
console.log(rect);
rect.print();

output:

{
  length: 10,
  width: 20,
  perimeter: NaN,
  area: NaN,
  print: [Function: print]
}
  • `this` is the global object, hence `this.length` is `undefined`. – D. Pardal Jul 14 '20 at 11:18
  • See the [linked question's answers](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations). For your example, I figure you probably want accessor properties `get perimeter() { return 2 * (this.length + this.width); }` (and similar for `area`). – T.J. Crowder Jul 14 '20 at 11:19
  • thankyou guys now i got it – ShivShankar Mishra Jul 14 '20 at 11:57

0 Answers0