Comment on Node.js Best PracticesparentComments−aikah11y Cant you just "return this;" to avoid using "new"?THIS will be the global scope if a function meant to be a constructor is called without new.Try that in your console function Foo(){this.foo = "bar";return this} then do : Foo() ; it will return window;so the answer is no.−greg5green11yThe answer is yes if you do: Foo.call({});−LazerBear11yThat's a cool trick, though 'instanceof' won't work in this case.−cygx11yYup. The proper way to emulate new is Foo.call(Object.create(Foo.prototype))−LazerBear11yDouglas Crockford, is that you? Oh the lengths people will go to avoid using 'new'...I wonder if any linters out there warn when they see something like: something = SomeCapitalizedFunction() Because forgetting to use 'new' is really the only thing I could think of that makes this pattern dangerous.−jdlshore11yYes, jslint and jshint both do, by default, iirc. They'll also warn on the opposite (using 'new' with a function that doesn't start with an uppercase letter).−LazerBear11yAh that's fantastic, i've been using them for a while and never noticed.
Comments
THIS will be the global scope if a function meant to be a constructor is called without new.
Try that in your console
then do : it will return window;so the answer is no.
The answer is yes if you do:
That's a cool trick, though 'instanceof' won't work in this case.
Yup. The proper way to emulate new is
Douglas Crockford, is that you? Oh the lengths people will go to avoid using 'new'...
I wonder if any linters out there warn when they see something like:
Because forgetting to use 'new' is really the only thing I could think of that makes this pattern dangerous.Yes, jslint and jshint both do, by default, iirc. They'll also warn on the opposite (using 'new' with a function that doesn't start with an uppercase letter).
Ah that's fantastic, i've been using them for a while and never noticed.