Question

Most places where I have seen prototypes defined for a constructor it was done like so.

var Person = function(){
    this.stuff = stuff;
}
Person.prototype.doSomething = function(){console.log("something")}
var john = new Person();

But to me, coming from Java it seems more intuitive to define it directly inside the constructor.

var Person = function(){
    this.stuff = stuff;
Person.prototype.doSomething = function(){console.log("something")}
}
var john = new Person();

But the fact that I have never seen it done that way before makes me wonder if there is something wrong with doing it that way. Does it cause any problems I haven't foreseen?

Was it helpful?

Solution

The entire point of setting a function on a "constructor" in JavaScript is so that it's set for the prototype chain when an instance is accessed.

Example A
function Foo() {...}
Foo.prototype.bar = function () {...}
var foo = new Foo();
foo.bar(); //references the shared function on the constructor

As an alternative, functions can be set directly on instances in the constructor.

Example B
function Foo() {
  this.bar = function () {...};
}
var foo = new Foo();
foo.bar(); //references the function set directly on the instance

The difference between these two methods is in how many functions are created.

Generating a thousand instances of Foo in example A will have exactly one bar method defined and used for all instances.

Generating a thousand instances of Foo in example B will have one thousand methods created. One for each instance. This can be useful for accessing scoped variables, but comes with the obvious performance cost.


If instead you add the function to the prototype inside the constructor...

Example C: (don't ever do this)
function Foo() {
  Foo.prototype.bar = function () {...};
}
var foo = new Foo();
foo.bar(); //references the shared function on the constructor

You get the worst of both methods. You're completely unable to make use of scoped variables, because the prototype is shared, so every instance will overwrite the function and scope that's available, and you're generating a new function for each instance, and you're throwing out all the existing functions.

Don't ever write JavaScript in that manner.


tl;dr:

Is it bad to access the constructor prototype within the constructor?

Yes

Licensed under: CC-BY-SA with attribution
scroll top