31

When I use the latest (1.0) release of coffee-script, a simple javascript output looks like this (by default):

(function() {
  var a;
  a = 1;
}).call(this);

What does .call(this) do and what would be the reason to add it?

PandaWood
  • 8,086
  • 9
  • 49
  • 54
  • can you also show us the code that yields this js? – Gabi Purcaru Dec 28 '10 at 00:55
  • 1
    My guess is that it's the simplest way to make all variables have local function (not global) scope by default and to give access to parent scope through 'this' – miensol Dec 28 '10 at 01:00
  • 2
    This is an excellent article on the subject of namespacing your JS: http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/ – Darren Newton Dec 28 '10 at 01:00
  • @Gabi Purcaru: This would be generated by the CoffeeScript `a = 1`. – Chuck Dec 28 '10 at 01:01
  • If you wonder why `.call(this)` was used instead of the normal IIFE call, see [my answer](http://stackoverflow.com/a/21736430/1048572) on "Why write “.call(this)” at the end of an javascript anonyms function?" – Bergi Feb 12 '14 at 18:26
  • See also the good answers at [Pattern for CoffeeScript modules](http://stackoverflow.com/q/5211638/1048572) – Bergi Dec 08 '14 at 00:54

2 Answers2

34

It's a way to make sure that the compiled CoffeeScript has its own scope for variable names. This has benefits in terms of efficiency and simplicity (you know you the generated JavaScript won't stomp on variables used by other code). You can disable it with the --bare (or -b) option to the CoffeeScript compiler.

The reason for the call(this) is just to ensure that the CoffeeScript has the same this as the scope where it's placed, because functions don't normally inherit their this object from the surrounding context.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 5
    How is this different than a self exec funct? Like: (function() { /* Code */ })(); – qwertymk Dec 28 '10 at 06:04
  • 8
    The self-executing function loses it's notion of `this`, when it doesn't happen to be loaded in a browser context. Some CommonJS platforms evaluate loaded files with a specific `this`. – jashkenas Dec 28 '10 at 17:10
  • 2
    I fully understand the variable scope reasons, but I'm curious to know how there's an efficiency benefit. Are you referring to efficiency of the compiler, or of the generated JavaScript? – Matt Ball Jun 09 '11 at 05:55
15

It's creating a function and then calling itself with the parent function/objects scope.

.call and .apply are different methods of invoking a function. You basically created a function that does nothing except set a=1 within its own scope.

In javascript you need to realize that every function is a object, and this is what refers to the current object/function. Using .call(this) overrides this from within the function and replaces it with the one from the calling context.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
HaMMeReD
  • 2,440
  • 22
  • 29