Search code examples
javascriptstack-overflow

Getting a stack overflow in a setter function


I wrote a class in JavaScript to figure out how classes work. I have run into an error with setter functions. I defined the following class that represents a simple polygon with the number of sides, the lengths of the sides, and the type of polygon:

class polygon{
    constructor(numbOfSides=0, sideLens=[], type=null){
        this.numberOfSides = numbOfSides;
        this.sideLengths = sideLens;
        this.typeOfPoly = type;
    }

    set numberOfSides(numbOfSides=0){
        if (numbOfSides > 0) return undefined;
        this.numberOfSides = numbOfSides;
    }
    set sideLengths(sideLens=[]){
        if (sideLens.length == 0) return undefined;
        this.sideLengths = sideLens;
    }
    set typeOfPoly(type=null){
        if (type == undefined) return undefined;
        this.typeOfPoly = type;
    }
    get numberOfSides(){return numberOfSides;}
    get sideLengths(){return sideLengths;}
    get typeOfPoly(){return typeOfPoly;}
    calcPerimeter(){
        let counter = 0;
        for (let item of sideLengths){
            counter += item;
        }
    }
}

const myPolygon = new polygon(4, [4, 6], "Rectangle");
console.log(myPolygon.numberOfSides);
console.log(myPolygon.calcPerimeter());

When creating an instance of the object I receive a stack overflow error:

 set sideLengths(sideLens=[]){
                ^
 RangeError: Maximum call stack size exceeded

why would I be getting an error like this?


Solution

  • Setter is special function that handles assignment. You code is equivalent to following function call.

    setSideLengths(sideLens=[]){
        if (sideLens.length == 0) return undefined;
        this.setSideLengths(sideLens);
    }
    

    It recursively calls itself, thus the call stack overflow.

    If you wanna save the value somewhere, the conventional way is to save it with a underscore prefixed property of the same name.

    set sideLengths(sideLens=[]){
        if (sideLens.length == 0) return undefined;
        this._sideLengths = sideLens;
    }