Search code examples
javascriptprototypegetter-settersetter

Javascript setter function with prototyping


I am learning Javascript. When I try to use setters with prototyping I am getting an error

TypeError: cir1.radiusToCircle is not a function

var Circle = function(radius){
    this._radius = radius;
}

//prototype

Circle.prototype ={
    set radiusToCircle(rad) { this._radius = rad; },
    get radiusFromCircle() { return this._radius;},

    get area() { return (Math.PI * (this._radius * this._radius));}
};

var cir1 = new Circle(5);

cir1.radiusToCircle(14);

What am I missing here?

Thanks in advance.


Solution

  • To use a setter you need to set the property directly, not pass it through like a function argument. Setter MDN Docs

    cir1.radiusToCircle = 14;