JavaScript (7) Closure, Modules and API

1. Closure:

You can think that closure is a way to "remember" and continue to access a function's scope (its variables) even once the function has finished running.

function greet_with(greeting) {
  function greet(name) {
    // close greeting
    console.log(greeting + " " + name);  
  }
  return greet;
}

var hello = greet_with("hello");
hello("bob");

var hi = greet_with("hi");
hi("bob");

2. Let identifier and block scope:

{
    var a = 10;
    console.log("inside: " + a.toString()); // inside: 10
}

console.log("outside: " + a.toString()); // outsize: 10

As the program which is show above, We can access the value of the variable outside the block but things is different if you declare the variable using let identifier:

{
    let a = 10;
    console.log("inside: " + a.toString());
}

console.log("outside: " + a.toString()); // !! Error

let identifier creates a block scope and the variable "a" is attached to that scope which means we can't access the variable outside the scope of that block.


3. Closure and callback function:

for(var i=0; i<10; i++) {
    setTimeout(function(){ 
        console.log(i) 
    }, i*1000);
}

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

The program which is shown above prints 10 on the screen each second gradually because the callback access i after the loop is over.

Let's take another example:

for(let i=0; i<10; i++) {
    setTimeout(function(){ console.log(i) 
    }, i*1000);
}

This time the program prints 0 to 9 on the screen each second. let identifier creates a block scope for i so the callback can access the block after the loop is over.


4. Modules:

Povide API for specific operation:

var User = function() {
  // members
  var name;
  var pwd;

  var doLogin = function(user, password) {
    name = user;
    pwd = password;
    console.log("Other process...")
  };

  // wrap the function with an object
  var publicAPI = {
    login: doLogin
  };

  // export the object
  return publicAPI;
};

var cooper = User();
cooper.login("cooper", "bear");

Typically, we create an object which is used to wrap and expose API. The scope of the variable is kept and we can access the value of the variable with that API indirectly.


Reference

[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)

留言

熱門文章