I'm doing a tuts tutorial on intel xdk and parse and one of the source files has this syntax I've never seen anywhere. The file itself opens with a function that not only has no name, but is declared inside regular parentheses. Can someone explain and/or link to some online resource that explains this?
(function (credentials) {
var exports = {};
var baseUrl = 'https://api.parse.com/1/classes/article/';
exports.articles = function (params) {
params = params || {};
var artID = '';
if (params.ID) {
artID = params.ID;
}
var url = baseUrl + artID;
return $.ajax({
url: url,
headers: {
'X-Parse-Application-Id' : credentials.apiKey,
'X-Parse-REST-API-Key' : credentials.apiSecret
}
});
};
return exports;
})
1 Answer 1
Your code snippet as many pointed out, is most likely missing a pair of () at the end. With the (), it becomes a IIFE, this Wikipedia article pointed by Mike explains fairly clearly.
In brief, an immediately-invoked function expression is executed once your program encounters it. Consider the simple case below:
//Your awesome js
console.log(b); // undefined
(function() {
b = "cat";
})();
console.log(b); // cat. Since in the above IIFE, we defined a global variable b.
You can also pass parameters into the IIFE like this:
(function(input) {
console.log(input); // 5
})(5);
Your code above creates an "export" object and returns it. If you read the "Establishing private variables and accessors" section in the Wiki, you'll see how that is similarly used to nicely create "private" variables.
Comments
Explore related questions
See similar questions with these tags.
()on the end because then it would be an IIFE.