Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the structure of underscore.js code

I saw this pattern in the underscore source code and many other open source JavaScript projects :

(function() {
 // the library code
}).call(this);

Anyone can explain what this pattern do ? and what is the benefits of using it ?

Why not just :

(function() {
 // the library code
}());
like image 363
Salah Eddine Taouririt Avatar asked Jan 27 '14 17:01

Salah Eddine Taouririt


People also ask

What does _ do in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is _ each in JavaScript?

The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.

What is underscore argument in JavaScript?

The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter. A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter".


1 Answers

Since both are equivalent in normal context I looked into the source and it was changed from the form you suggest to the current form 2 years ago with the following check-in comment:

"Added explicit definition of global context for compatibility with Adobe JS"

https://github.com/jashkenas/underscore/commit/aa916b8cfe565dc206d85c4cb74fbb6c499067a7

The check-in logs for the first version of Underscore with this change claims "Improved Underscore compatibility with Adobe's JS engine that can be used to script Illustrator, Photoshop, and friends."

http://underscorejs.org/ Version 1.4.3

So this change seems to have been made because Adobe's JavaScript engine did not conform to ES3 or ES5 at the time but with this change Underscore was made compatible with their variant.

If you are not planning on running your module in Adobe JS then you can use either form. If you are then it appears Adobe JS requires the form used by Underscore.

like image 72
chuckj Avatar answered Oct 25 '22 02:10

chuckj