I know that the following is valid in JavaScript:
function Rectangle(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
Rectangle.getRight = function(rect) { return rect.x + rect.w; };
Rectangle.sides = 4;
I've read about how this is a way to emulate static methods/properties on a "class" in JavaScript. With the code above, any time I want to get the right side of a rectangle I can do this:
var rect = new Rectangle(0, 0, 10, 20);
Rectangle.getRight(rect); // 10
These properties could be defined on the Rectangle's prototype as well:
Rectangle.prototype = {
getRight() { return this.x + this.w; },
sides:4
};
Then I could do the following:
rect.getRight(); // 10
Obviously using a prototype results in cleaner looking code, but prototype inheritance can be problematic. Maybe I have a Hitbox class which is basically a rectangle, so it should inherit from the Rectangle prototype, but I don't need the sides property, so inheritance in this case creates bloat. The Rectangle prototype has properties that Hitbox doesn't need, and the Hitbox prototype has methods that Rectangle doesn't need, but I can use Rectangle.getRight on instances of both classes.
My question is whether it is good practice to define methods and properties on functions. Also, are there performance issues with this approach? Would it be preferable to define getRight on an Object that acts as a container for rectangle methods rather than on a Function? Basically, I want to know if there are any reasons not to use this design pattern.