What is the preferred idiom for defining a class in JavaScript? I could define a constructor function for complex numbers as follows:
function Complex(real, imag) {
this.real = real;
this.imag = imag || 0.0;
this.add = function(other) {
this.real += other.real;
this.imag += other.imag;
return this;
}
}
or I could do the following:
function Complex(real, imag) {
this.real = real;
this.imag = imag || 0.0;
}
Complex.prototype = {
add : function(other) {
this.real += other.real;
this.imag += other.imag;
return this;
}
}
Since neither textbook JavaScript : The Good Parts nor JavaScript The Definitive Guide define classes the first way I suspect these are not equivalent -- I suspect I need use prototype
if I plan on using inheritance. This seems a little murky to me -- can anyone clarify this?
I know I could use the Object.create()
method suggested in the aforementioned texts and do things the prototypical way, but I don't see folks doing this in practice much.