2

I get the use of JavaScript's new operator, anonymous functions, and use of functions as first class citizens (i.e. passing functions as parameters, using functions as return values, etc..) And I thought of doing a weird combination of these.

function foo(s) {
    return function () {
        alert(s);
    }
}

var bar = foo('bar');
var baz = new foo('baz');

bar();
baz();

Both calls bar() and baz() behave similarly (i.e. alert's 'bar' and 'baz' respectively).

Is there really a difference between variable = func() vs variable = new func() when func() returns an anonymous function?

sampathsris
  • 21,564
  • 12
  • 71
  • 98
  • 4
    @Kooilnc this isn't a duplicate of the proposed question, this one is more specifically talking about the use of `new function()`. – James Aug 16 '14 at 16:58
  • Only difference is that with `new`, there's an object being created and subsequently ignored by your code. – cookie monster Aug 16 '14 at 17:03
  • @cookiemonster: That indeed is a duplicate. But that question is made too complex by the inner use of `new` operator. After posting the question I have found an answer, which answers this question as well: http://stackoverflow.com/a/6491067/1461424 – sampathsris Aug 16 '14 at 17:08
  • To be more precise, if the function explicitly returns an object, it doesn't matter if you call it with `new` or not, the return value will always be that object (unless you have `return this;` because `this` differs). – Felix Kling Aug 16 '14 at 17:09
  • `new` creates an object and calls the function with `this` set to this new object. If the function does not return an object itself, the result of `new ..` will be the object created by `new` (`this` inside the function). If the function does return an object, the result of `new ..` will be that object. So in this case: it doesn't matter. – deceze Aug 16 '14 at 17:10
  • 1
    @Krumia: It's no more complex since what the function you're returning does plays no role in the actual use of `new` that you're asking about. The returned function could be a no-op, and the answer would be the same. – cookie monster Aug 16 '14 at 17:10
  • 1
    @cookiemonster: I have no argument that this is a dupe. I'm merely suspecting that someone new to JavaScript will be confused by inner use of `new`. Otherwise the question is same. – sampathsris Aug 16 '14 at 17:12
  • I see. Just wanted to make sure you knew that there wasn't some side effect going on there because of the inner `new`. – cookie monster Aug 16 '14 at 17:13
  • @James my bad (sloppy reading, too much code lately). – KooiInc Aug 16 '14 at 17:17

0 Answers0