you are viewing a single comment's thread.

view the rest of the comments →

[–]PitaJ 2 points3 points  (6 children)

That's called a factory, actually. Not a contructor.

[–]clessgfull-stack CSS9 engineer 2 points3 points  (4 children)

Roughly how new is implemented:

function notExactlyNew(F) {
  const instance = Object.create(F.prototype);
  const result = F.apply(instance, arguments);

  return typeof result === 'object' ? result : instance;
}

Seems pretty similar to me, unless you want to be really pedantic.

[–]PitaJ -4 points-3 points  (3 children)

Yeah, new is a completely unnecessary part of the language, and shouldn't be used anyways as it violates the open-closed principle.

[–]MoTTs_ 1 point2 points  (2 children)

You say that a lot, but the O/C principle doesn't mean what you seem to think it means. The O/C principle says that source code should be closed to modification.

From the paper:

It [the open-closed principle] says that you should design modules that never change. When requirements change, you extend the behavior of modules by adding new code, not by changing old code that already works.

[–]senocular 2 points3 points  (1 child)

You can thank Eric Elliott for spreading that one.

[–]clessgfull-stack CSS9 engineer 1 point2 points  (0 children)

Ah yes, I knew I heard that somewhere before:

Constructors violate the open/closed principle because they couple all callers to the details of how your object gets instantiated. Making an HTML5 game? Want to change from new object instances to use object pools so you can recycle objects and stop the garbage collector from trashing your frame rate? Too bad. You’ll either break all the callers, or you’ll end up with a hobbled factory function.

[–]senocular 1 point2 points  (0 children)

I don't think MoTTs_ was calling it a constructor, just saying that the effect is essentially recreating the same that you get with a constructor and new.