0

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.

wcochran
  • 10,089
  • 6
  • 61
  • 69
  • 4
    This is a duplicate of so, so many questions. – Etheryte Jul 31 '14 at 16:23
  • I figured as much, but I couldn't find an *exact* answer. Maybe someone could just confirm my suspicions, and I can remove the question. – wcochran Jul 31 '14 at 16:26
  • There are no real classes in javascript, just new instances of functions. When prototyping you create a new property that inherits, so when the "parent" is changed, so it the "child" etc. – adeneo Jul 31 '14 at 16:29
  • Yes, I am well aware that JS uses prototypical inheritance. The notion of a class still exists I.e. objects that have the same prototype are considered to be of the same class. – wcochran Jul 31 '14 at 16:33
  • Maybe the following helps: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 using prototype produces code that can be better optimized, has recognizable inheritance patterns and will consume less memory when creating a lot of instances. If you reply to comments it's better to use @ or the person commented will not be notified – HMR Jul 31 '14 at 17:18
  • Thanks @HMR, so I guess the `this.add = function(other) {...}` is *not* adding the method to `Complex.prototype`, but every object gets its own copy of the function. Thanks, now I get it. – wcochran Jul 31 '14 at 17:28

1 Answers1

0

In the first example, every new object get's its own copy of the add() method.

In the second example, every new object share's a single copy of the add() function via the prototype.

Obviously the latter is more efficient.

wcochran
  • 10,089
  • 6
  • 61
  • 69