Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top