Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the javascript function wrapper (added in coffeescript) ".call(this)"

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?

like image 452
PandaWood Avatar asked Dec 28 '10 00:12

PandaWood


People also ask

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

How do I use CoffeeScript in HTML?

If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.


1 Answers

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.

like image 61
Chuck Avatar answered Sep 22 '22 11:09

Chuck