0

Let me put first two examples.

Example 1:

function Gallery() {
    this.a = "I am 'A'";

    this.trace = function() {
        console.log(this.a);
    }
}

Example 2:

function Gallery() {
    this.a = "I am 'A'";
}

Gallery.prototype.trace = function () {
    console.log(this.a);
}

Obviously, both things do the same. My question is: is there any drawback to using the method definition in the constructor function over the prototype one? What exactly is the difference anyway?

Is the prototype more memory friendly? I assume that if I define the method inside the constructor function, every single Gallery instance will have its 'own instance' of the method so will consume more memory while the prototype defines only one function that's shared across all the Gallery instances. Is this correct?

Thanks a lot!

Fygo
  • 4,555
  • 6
  • 33
  • 47

2 Answers2

2

The method definition in constructor is slower because it's executed every single time you create a new object.

On the other hand, with a prototype, the VM will be able to optimize access to it, to optimize the functions (since they're shared - it wouldn't be able to do if it every instance had its own functions).

(not going too much into details because it's been explained already, but basically, VMs (I know v8 does that, not sure what others do) will usually a "hidden class" for every prototype, with optimized fields, instead of just having it as a map of any => any)

This also allows a lot more of flexibility to add functions at a later time.

The only good thing about adding methods on the object is that you can fake "private" fields more easily.

Ven
  • 19,015
  • 2
  • 41
  • 61
0

You're right that each Gallery object will have its own .trace() function object if you put .trace() in the constructor, so it's more efficient to make methods in the .prototype object unless you absolutely want to use encapsulation to hide your arguments passed into the constructor instead of saving them as properties on the instance. The .prototype object is also easier for the browser to optimize.

Both methods are almost indistinguishable in practice unless a coder tries to inspect your JavaScript code with his JavaScript console in which case it'll be much easier for them to read the methods to be on the .prototype object instead of inside the constructor altogether with everything. Take of that what you will.

Noble Mushtak
  • 1,784
  • 10
  • 22