Created
August 26, 2013 06:46
-
-
Save vasco3/6338657 to your computer and use it in GitHub Desktop.
// The concept of self-executing functions encapsulating code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The concept of self-executing functions | |
// 1. Basic self-executing functions for encapsulation | |
// | |
// Suppose you have some JS code like this: | |
var foo = "inner"; | |
console.log(foo); | |
// You worry that the external world may also have defined a foo variable. | |
// To protect your code, you can encapsulate it by putting it in a | |
// self-executing function. | |
var foo = "outer"; | |
(function() { | |
var foo = "inner"; | |
console.log(foo); | |
})(); | |
console.log(foo); | |
// This will print: | |
/* | |
inner | |
outer | |
*/ | |
// Let’s break this down bit by bit. The inside is just an anonymous | |
// function definition. Let’s assign it to a variable. | |
var anon = function () { | |
var foo = "inner"; | |
console.log(foo); | |
}; | |
// We enclose this function definition in parentheses, and then immediately | |
// execute it by adding another two parens at the end. We also need a | |
// semicolon as the expression is ending. | |
(function() { | |
var foo = "inner"; | |
console.log(foo); | |
})(); | |
// 2. Passing in variables to a self-executing function | |
// | |
// Now that we’ve set up a wall, we can do something more sophisticated by | |
// passing in specific variables from the enclosing scope. | |
var bar = "allowed"; | |
(function(aa) { | |
var foo = "inner"; | |
console.log(foo + " " + aa); | |
})(bar); | |
// This prints | |
/* | |
inner allowed | |
*/ | |
// 3. Passing in and receiving variables from a self-executing function. | |
// | |
// Now we’ll return an object as well, converting the inside into a proper | |
// function. | |
var bar = "allowed"; | |
var result = (function(aa) { | |
var foo = "inner"; | |
var out = foo + " " + aa; | |
console.log(out); | |
return {"val": out}; | |
})(bar); | |
console.log(result); | |
// This prints | |
/* | |
{ val: ’inner allowed’ } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment