Mims H. Wright
Mims H. Wright

Reputation: 3037

If I define methods on the prototype, how do I call them in the constructor?

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?

Upvotes: 0

Views: 119

Answers (1)

I Hate Lazy
I Hate Lazy

Reputation: 48819

Your last way is correct, but you don't need the quotes.

var A = function (options) {
    this.initialize(options); 
};
A.prototype.initialize = function (options) {
    // do something with options.
};

Assuming A is invoked as a constructor, this is a reference to the new object being constructed, and its prototype chain is already established, so it already has access to the initialize method.

Of course there's no requirement that initialize be 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.

var A = function (options) {
    initialize(this, options); 
};
function initialize (obj, options) {
    // do something with options.
};

or you could just put the initialization code right in the constructor function.

Upvotes: 6

Related Questions