-1

I just took a look at the underscore.js source code and when i strip the source code down to its bare containing IIFE it looks like this:

(function() {

}.call(this));

I always used the syntax with outer parantheses (function() {}).call(this); and wondered if this syntax is also valid and common?

Nick Russler
  • 4,608
  • 6
  • 51
  • 88
  • Yes this syntax is correct :) – Oleksandr T. Feb 24 '15 at 12:50
  • 1
    Why would the outer parentheses be wrong? – Frédéric Hamidi Feb 24 '15 at 12:51
  • @FrédéricHamidi i was expecting that the outer paranthesis is needed so the anonymous function can be treated as an expression e.g. `(function() {}).call(this)` or `+function() {}.call(this)`. But why does `(function() {}.call(this))` execute but `function() {}.call(this)` does not? – Nick Russler Feb 24 '15 at 12:56
  • 2
    See the duplicate on what this construct does. If you're only looking for the parenthesis syntax, see [Location of parenthesis for auto-executing anonymous JavaScript functions?](http://stackoverflow.com/q/3384504/1048572) – Bergi Feb 24 '15 at 13:02

1 Answers1

2

If you're asking about the location of the outer ) specifically, then whether it's located immediately after the closing brace or after the entire expression doesn't matter for the most part. Either way doesn't make a difference to how the IIFE is executed.

The only difference here is the .call(this), which is invoked as a member of the function expression — a typical IIFE has just the inner parentheses immediately following the closing brace. The reason .call(this) is used is detailed in a number of other answers including this one.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • But `function() {}.call(this)` can't be executed, i know the trick via `+function() {}.call(this)` but why would wrapping it inside paranthesis change how the inner expression is executed? – Nick Russler Feb 24 '15 at 12:53
  • 3
    @Nick Russler: Wrapping it inside parentheses or `+`ing it tells the parser that it's a function expression, not a function declaration. – BoltClock Feb 24 '15 at 12:54
  • So it's just a syntax thing. It seemed weird to me that enclosing paranthesis could change how the inner code is executed. – Nick Russler Mar 04 '15 at 12:47