I understand that it is good practice to assign methods directly to a class’ prototype so that they are not redefined every time the function is called.
var A = function () {
this.prop = "A property";
}
A.prototype.method = function () {
return "A method";
}
Say I want to call a method defined in this way in the constructor. Is this possible?
var A = function (options) {
initialize(options); // initialize is undefined.
}
A.prototype.initialize = function (options) {
// do something with options.
}
Creating a stub method inside the constructor doesn’t work because it gets called instead of the prototype’s version of the function. The only way I have been able to get this to work is to reference the function via bracket syntax this["initialize"]() which seems pretty inelegant.
var A = function (options) {
this["initialize"](options); // function isn't defined yet but will be soon!
}
A.prototype.initialize = function (options) {
// do something with options.
}
This seems pretty janky and would probably not be the most optimal way to call this function. Is there another way or am I missing something?
Your last way is correct, but you don’t need the quotes.
Assuming
Ais invoked as a constructor,thisis a reference to the new object being constructed, and its prototype chain is already established, so it already has access to theinitializemethod.Of course there’s no requirement that
initializebe prototyped. If it’s not intended to be called more than once, then it may make more sense to define it as a stand alone function.or you could just put the initialization code right in the constructor function.