Sunday, November 3, 2013

Pro Nodejs book



What Are Closures in JS?

Closures are functions that inherit variables from their enclosing environment.

(function() {
   var clickCount = 0;

   
   $('button#mybutton').click(function() 
   {
       clickCount ++;
       alert('Clicked ' + clickCount + ' times.'); 
   });
}()); 


You can do event-driven programming without having to maintain the state by passing it around to functions by using the closure pattern.

Event-driven programming is a programming style whereby the flow is determined by the occurrence of events. Programmers register callbacks to be used as event handlers, and the system invokes these handlers when those events occur. This model of programming has some advantages over the traditional blocking paradigm where you have to use multiple processes or threads.

JavaScript is a powerful language, which is well suited for this style of programming, mainly because it has first-class functions and closures. 

Functions are first class objects in javascript
Functions in javascript are first class objects. This means that javascript functions are just a special type of object that can do all the things that regular objects can do.
Here are a few of the important objects things that you can do with a function in javascript.
A function is an instance of the Object type:
  1. function feedCat(){
  2.     alert("Kibble, tinned food and water");
  3. }
  4. alert(feedCat instanceof Object);
A function can have properties and has a link back to its constructor method:
  1. feedCat.food = "kibble";
  2. alert(feedCat.food);
  3. alert(feedCat.constructor);
You can store the function in a variable:
  1. function feedCat(){
  2.     alert("Kibble, tinned food and water");
  3. }
  4. var eveningChore = feedCat;eveningChore();
You can pass the function as a parameter to another function:
  1. function doEveningChores(chores){
  2.     for(var x=0; x<chores .length; x++)
  3.         chores[x]();
  4. }
  5. doEveningChores([feedCat]);
You can return the function from a function:
  1. function tonightChores(){
  2.     return feedCat;
  3. }
  4. var tonight = tonightChores();
  5. tonight();

Can reduce repetitive code

... from - http://helephant.com/2008/08/19/functions-are-first-class-objects-in-javascript

Object methods are properties that contain functions

  1. var sabby = {
  2.      name : "Sabby",
  3.      species: "cat",
  4.      hello : function() { alert("hissss")}
  5. };
This was pretty clever of the javascript language designers because it meant that they didn’t need to do anything special to support object methods. This is part of the reason why javascript can have objects without having classes.




No comments:

Post a Comment