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;
    }
}
Daniel
  • 9,491
  • 12
  • 50
  • 66
  • 2
    Just create a function and assign it to properties on the prototypes. – Pointy Feb 26 '16 at 04: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. – jfriend00 Feb 26 '16 at 04:27
  • Thanks for the help! –  Feb 26 '16 at 04:35

1 Answers1

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.

Ethan JC Rubik
  • 174
  • 1
  • 1
  • 12