I’ve seen a lot of explanations about javascript closures, just a few short demos, a long and obscure introduction, and a whole bunch of concepts about closures, but in the end I didn’t really understand what closures meant and what they did. It wasn’t until early last night, when I was learning node.js module development, that I suddenly understood. So write it down before you forget it later. Code source: Liao Xuefeng’s website node.js tutorial.

Directly on the code:

The hello.js file is a module. The name of the module is the file name (with the.js suffix removed), so the hello.js file is the module named Hello.

Let’s modify hello.js to create a function so that we can call it from somewhere else:

'use strict'; var s = 'Hello'; function greet(name) { console.log(s + ', ' + name + '! '); Module. exports = greet; // Module. Exports = greet;Copy the code

Here we can see that we run greet() directly; The result will be printed

'Hello,undefind! '

This is to be expected because we define a global variable s and greet() that uses the variable s.

Now, let's write another onemain.jsFile, callhelloThe modulegreetFunction:Copy the code
'use strict'; Var greet = require('./hello'); var greet = require('./hello'); var s = 'Michael'; greet(s); // Hello, Michael!Copy the code

The two pieces of code can be combined to look like this:

var s = 'Michael'; (function greet(name) { var s = 'Hello'; console.log(s + ', ' + name + '! '); })(s);Copy the code

Here we can see that there are two variables of s, but the result is still:

Hello, Michael!





Copy the code

The closure was created by accident, but we didn’t even know it. Now let’s look at the code above.

var s = 'Michael'; // This is the global variable defined

Copy the code
var s = 'Hello'; // This is the local variable defined in the greet() function



A closure is a function that defines global variables and local variables, so we can call global variables in a function, but we can't access variables in a function in a global scope, so we'll change the code a little bit

Copy the code
var n = 'Michael'; (function greet(name) { var s = 'Hello'; console.log(s + ', ' + name + '! '); })(n); console.log(s);Copy the code

If we access s directly inside the function, what will be the result?

Uncaught ReferenceError: s is not defined

This way we can be sure that variables within the function cannot be accessed globally, and the closure is complete.

If there is any mistake, please point out actively, thank you very much!!

 Copy the code
 Copy the code