Sachith Muhandiram
Sachith Muhandiram

Reputation: 2972

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.

Upvotes: 2

Views: 91

Answers (2)

Thaw
Thaw

Reputation: 861

What you are doing may work, but I don't know the set/get commands you are using and whether or not overloading the function is a good idea.

From the docs, it looks like the set/get will bind a callback that will run some unrelated code when you assign the member variable directly. If that's what you are trying to do, you don't need a prototype function.

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

Circle.prototype.getRadiusToCircle = function() {
    return this._radius;
}

Circle.prototype.setRadiusToCircle = function(rad) {
    this._radius = rad;
}

Circle.prototype.overloadRadiusToCircle = function(rad) {
    if(rad != null) {
        this._radius = rad;
    } else {
        return rad;
    }
}

Circle.prototype.area = function() {
    return (Math.PI * (this._radius * this._radius));
}

For example

var Circle = function(radius){
    this._radius = radius;
    this._area = Math.PI * (radius * radius);
}

Circle.prototype = {
    set _radius(radius) {
        this._area = Math.PI * (radius * radius);
    }   
}

Circle.prototype.getArea = function() {
    return _area;
}

Upvotes: 1

ShadowCommander
ShadowCommander

Reputation: 181

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;

Upvotes: 1

Related Questions