1

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?

3
  • 7
    No, that is not correct. The second scenario would create a new Model every time loginControllerInstance.doSomething is executed. Commented Apr 9, 2015 at 15:59
  • 2
    The method itself, doSomething, is defined only once with the prototype, but its contents are still reevaluated with each call. With #2, every use of login.doSomething() would create a new Model(). Commented Apr 9, 2015 at 16:00
  • Is this actually what you were asking? or was there a problem you were trying to solve. Seems kinda silly to have an answer so short. Commented Apr 9, 2015 at 16:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Currently learning JS and totally overlooked that. The .call() advice is pretty neat, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.