-1

In lot's of JavaScript libraries I see the following code:

(function(context){


})(this);

Why do these libraries use this? And what does this code do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tijme
  • 39
  • 2
  • 24
  • 41
  • http://benalman.com/news/2010/11/immediately-invoked-function-expression/ and `this` references the global object. – Fabrício Matté Jun 05 '14 at 17:55
  • On the "root" `this` is the global object... `window` in the browser, not so in node, so it decouples the library from the platform it's running on. – spender Jun 05 '14 at 17:55
  • I'd argue that this isn't a dupe of the marked question. Specifically, it doesn't address passing in `this`. I'd be surprised if this wasn't answered elsewhere. – spender Jun 05 '14 at 17:57
  • I don't think this is a duplicate ether. In the marked duplicate question it's not about the context. – Tijme Jun 05 '14 at 18:02
  • You need to indicate what "this" is a little more clearly to consider reopening. Nobody can tell the difference because the post body is so vague. – Brad Koch Jun 11 '14 at 03:25
  • What I posted was actually the whole Javascript file. So this would contain this.document, this.window etc. – Tijme Jun 12 '14 at 18:18

1 Answers1

1

That is an IEFE function which receives this as a parameter.

What it does is avoid scoping/closure issues by referring to context instead of this which varies when used in different places.

By referring to context you can be sure that it will remain this passed as argument and nothing else. But if you use this directly in the code, then closure and scoping issues will arise.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95