0

In Javascript, is there any difference between calling new foo() and simply foo()?

In other languages, the new keyword is required, but in Javascript, since Objects are created via functions as constructors, the new keyword should be neither necessary nor beneficial in any way.

For instance:

function foo(){ 
    return { a:2, b:3, hello: 'world' }
}

If I call new foo(), it returns the same result as foo().

I know the newest ECMAscript spec has classes which would maybe need the new keyword, but I really only care about function object constructors.

PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • And http://stackoverflow.com/questions/8448890/trying-to-understand-the-new-keyword?rq=1 – The Archetypal Paul Apr 29 '14 at 19:56
  • If the function returns an object, then there is no difference between `new func()` and `func()`. I recommend to read the MDN documentation about `new`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new. – Felix Kling Apr 29 '14 at 19:56
  • And http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript?rq=1 – The Archetypal Paul Apr 29 '14 at 19:57
  • 1
    It's actually not a duplicate of that question. This question is about `foo()` and `new foo()`, the other is about `function() {}` and `new function() {}` which is the same as `foo` and `new foo`. – Felix Kling Apr 29 '14 at 20:00
  • I looked for that question, I swear I tried. – PitaJ Apr 29 '14 at 20:09
  • *"I know the newest ECMAscript spec has classes which would maybe need the new keyword"* That really is just syntactic sugar for constructor functions. The way how JS works internally doesn't change, it's still a prototype based language. – Felix Kling Apr 29 '14 at 20:20
  • The 'new' operator is key to implement prototypal inheritance. A good explanation of this here: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript Best. – E. Valencia Apr 29 '14 at 19:56
  • @FelixKling is right, this isn't a duplicate of the currently linked question. It is a duplicate of this one though: https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – lukkea Sep 02 '17 at 05:29
  • @lukkea I wouldn't call this a duplicate of that at all. This question is much more specific. The answer to this question might be in one of the answers to that question, but the questions are very different. – PitaJ Sep 04 '17 at 02:06

0 Answers0