Sebastian
Sebastian

Reputation: 1654

JavaScript Prototypal Object Efficiency in Node.js

I was wondering which of the following would be more efficient in a Node API

function LoginController() {
    this.model= new Model();
};
LoginController.prototype.doSomething = function() {
    this.model.doSomethingToo();
}

versus this:

function LoginController() {
};
LoginController.prototype.doSomething = function() {
    new Model().doSomethingToo();
}

As far as I understand prototypal objects in scenario #1 I would create a new Model every time I call new LoginController().

In scenario #2 I would create a new Model only once when creating the first new LoginController(). All next new instances would not create an other Model, because it was already created in the prototypal function.

Is that correct?

Upvotes: 1

Views: 42

Answers (1)

Kevin B
Kevin B

Reputation: 95022

No, that is not correct. The second scenario would create a new Model instance every time loginControllerInstance.doSomething is executed.

However, there are a few other ways that you could do this, depending on what exactly Model.prototype.doSomethingToo does, for example:

function LoginController() {
    this.model = {};
};
LoginController.prototype.doSomething = function() {
    Model.prototype.doSomethingToo.call(this.model);
}

This would never initialize a Model instance, instead, it would simply execute Model.prototype.doSomethingToo with a this equal to this.model

What's best will depend on what you are trying to do and how each constructor/prototype is setup.

Upvotes: 2

Related Questions