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?

6
  • can you also show us the code that yields this js? Dec 28, 2010 at 0: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, 2010 at 1:00
  • 2
    This is an excellent article on the subject of namespacing your JS: javascriptweblog.wordpress.com/2010/12/07/… Dec 28, 2010 at 1:00
  • @Gabi Purcaru: This would be generated by the CoffeeScript a = 1.
    – Chuck
    Dec 28, 2010 at 1:01
  • If you wonder why .call(this) was used instead of the normal IIFE call, see my answer on "Why write “.call(this)” at the end of an javascript anonyms function?"
    – Bergi
    Feb 12, 2014 at 18:26

2 Answers 2

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.

3
  • 5
    How is this different than a self exec funct? Like: (function() { /* Code */ })();
    – qwertymk
    Dec 28, 2010 at 6: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, 2010 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 9, 2011 at 5: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.