4 ms·
Cant you just "return this;" to avoid using "new"?
by iLoch 12y ago
Cant you just "return this;" to avoid using "new"?
- aikah 12y ago> 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.
- greg5green 12y agoThe answer is yes if you do: Foo.call({});
- LazerBear 12y agoThat's a cool trick, though 'instanceof' won't work in this case.
- cygx 12y agoYup. The proper way to emulate new is Foo.call(Object.create(Foo.prototype))
- LazerBear 12y agoDouglas 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.