2

Let's say I have two classes, one called Rectangle and one called Circle. Both classes have the values X and Y, is there a way to define the variables and functions once for both of the classes? Read the code below if it explains it better:

function Rectangle(msg, font){
    this.msg = msg;
    this.font = font;
}

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

Rectangle && Circle { 

/* had no idea how to write the line above, 
but basically for both the rectangle and the circle, 
there is this code so I don't have to rewrite it for both.*/

    this.position = function(x, y){
        this.x = x;
        this.y = y;
    }
}
3
  • 2
    Just create a function and assign it to properties on the prototypes. Commented Feb 26, 2016 at 4:21
  • 2
    It sounds like you want a base object called something like Shape that both Rectangle and Circle could inherit from and thus share one implementation of some common properties and/or methods. I'd suggest you read up about Javascript inheritance. Commented Feb 26, 2016 at 4:27
  • Thanks for the help! Commented Feb 26, 2016 at 4:35

1 Answer 1

3

Yes, there is:

//creating class shape
function Shape(x,y){
    this.x = x;
    this.y = y;
};
//set position function
Shape.prototype.position = function(x,y){
    this.x = x;
    this.y = y;        
};

function Rectangle(msg,font,x,y){
    //calling object Shape
    Shape.call(this,x,y);
    this.msg = msg;
    this.font = font;
}
//inheriting object Shape
Rectangle.prototype=Object.create(Shape.prototype);

function Circle(radius,x,y){
    //calling object Shape
    Shape.call(this,x,y);
    this.radius = radius;
}
//inheriting object Shape
Circle.prototype=Object.create(Shape.prototype);

You can now call any function defined in Shape from a Rectangle or Circle object. Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Thanks, Ethan!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.