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