Functions that require knowledge of the instance (the created object) should be added to the 'class' prototype, the prototype function assigned to the constructor function.
If you do
instance = new Class();
then any function foo
you added to the prototype of Class
can be invoked as
instance.foo()
and will have access to all instance variables of instance
through the this
pointer.
Functions added to the constructor function Class
are just members of the function object named as Class
and do not know of nor care for instances you might have created.
Usually, you add constants to the constructor functions. So if you create a class 'Color' and add it Color.BLACK = 0;
(or better
Object.defineProperty(Color, 'BLACK', { value: 0});
)
to make it immutable, yo can access it like Color.BLACK
.
It still can be useful to add functions to the constructor function. Doing so is like defining static functions in a Java class.
There are mainly three types of functions that should be placed at the constructor:
generic (helper) functions that do not need an instance, e.g. Number.isFinite()
Conversion functions like Color.compare(color1, color2)
. They allow working without an instance. However, they might internally create an instance and may use instance functions from the prototype.
Color.compare(color1, color2) {
var color1 = new Color(color1);
return color1.compare(color2);
}
- specific constructor functions. While it is possible to deliberately interpret the parameters passed to the constructor and determine what they might mean, it could be way more convenient, to have separate functions that create and return an instance based on different parameters:
Color.RGB = function (r, g, b) {
var instance = new Color();
instance.r = r;
instance.g = g;
instance.b = b;
instance.RGBtoYCC();
return instance;
}
Color.YCC = function (Y, Cr, Cb) {
var instance = new Color();
instance.Y = Y;
instance.Cr = Cr;
instance.Cb = Cb;
instance.CYYtoRGB();
return instance;
}
So you can create a 'red' color as either
var color = Color.RGB(255,0,0);
or as
var color = Color.YCC(0.29889978, 0.5, -0.1687);