Skip to content

Instantly share code, notes, and snippets.

@mjzone
Last active July 3, 2016 07:32
Show Gist options
  • Save mjzone/10eed805b3c2bad92793eeb725d78981 to your computer and use it in GitHub Desktop.
Save mjzone/10eed805b3c2bad92793eeb725d78981 to your computer and use it in GitHub Desktop.
// Functions are 'first-class' objects.
var myFunction = function(){
console.log("I have been called.");
}
myFunction.firstName = 'Manoj'; // we can attach attributes to functions because they are also objects.
console.log(myFunction);
// Functions can be anonymous.
setTimeout(function(){
console.log("hello, i have been called after 1 second.")
},1000);
// Function can be self executing.
(function(){
console.log("I have been called immediately.")
})();
// Encapsulation in JavaScript.
(function(){
var message = "hello world.";
})();
if(typeof message === 'undefined'){
console.log('I cannot access the value of message.')
} /* this demonstrates encapsulation in Javascript. Variables defined in the self executing function above
* cannot be accessed from outside. That function has it's own scope. */
// Functinos encapsulate and capture scope.
(function(){
var messages = ['hello', 'world'];
for (var i in messages){
setTimeout(function(){
console.log(messages[i]);
}, 10);
}
})(); // Result: world, world. gotcha!
// (setTimeout is called inside the scope of 'for' block. The value of i inside the 'for' block is passed to SetTimeout.)
(function(){
var messages = ['hello', 'world'];
for (var i in messages){
setTimeout((function(myVal){
console.log(messages[myVal]);
})(i), 10);
}
})(); // Result: hello, world. (We are now passing value of i in each iteration to the function as a local parameter myVal.
// Each time its separate scope and keep it's myVal values separately. )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment