1

Background: I am working in Knockout and have implemented a custom component loader. Specifically, I am implementing the loadComponent and createViewModel methods for dependency injection purposes. So basically, I determine the appropriate constructor by some convention and then call new on it with the required dependencies.

My question: when I have this..

function model(arg1, arg2) {
    this.foo = arg1;
    this.bar = arg2;
}

What exactly is the difference between:

var instance = new model(arg1, arg2);

and:

var instance = {};
model.apply(instance, [arg1, arg2]);

Both seem to have the same result. As for my specific use case, I want to do something like:

var instance = {};
model.apply(new Proxy(instance, handler), [arg1, arg2]);

Where handler would translate something like:

this.foo = 'bar';

into:

this.foo = ko.observable('bar');

..to abstract the clunky observable syntax of Knockout.

  1. Is this a terrible idea?
  2. Is there a better / easier way?
  3. What the implications of doing this instead of new?
  • 2
    I'm not sure whether or not the differences affect your use case or not, but there is definitely some additional stuff that happens when you call `new model` that doesn't happen with `model.apply`. See http://stackoverflow.com/a/3871769/560114. – Matt Browne Jul 16 '16 at 02:13
  • If you depend on `model.apply({} ...)` and you get weird behaviour at some point, I wouldn't be surprised in the slightest. Generally, I would recommend avoiding clever code. MattBrowne's link has great information about behaviours of `new` that you need to be aware of. – Mulan Jul 16 '16 at 08:40
  • Thank you for the comments and links. Sounds like if I don't care about the prototype chain (I don't in this case), I don't have anything to worry about. – Andrew Tevington Jul 17 '16 at 17:16

0 Answers0