Take you to understand the most authentic and easy-to-understand closures, mom is no longer afraid of the interviewer asking questions

Understanding closures

Overshadowed Cloth

First, what is a closure? You can understand it as sharing variables in two disconnected scopes.
Give a chestnut:

function foo() {
	var a = 10;
	function bar () {
		console.log(a);
	}
	return bar;
}
foo()();// 10 请注意这里的10怎么来的。

Have you noticed that the variables inside the foo function are used below the global scope, this is the closure! ! !

The function bar scope covers the function foo. We pass the reference of the bar function as the return value, and then we can use the function reference of foo in the reference.

The magic of the closure itself is not here. Generally speaking, the scope of foo is collected by the garbage collector after the execution of the foo function is completed, but it is not here, because there is a reference to the scope of foo Passed out, that is, bar, bar has a pointer to the a variable, so the scope of foo is not recovered after the foo function is used. bar still holds a reference to the scope of foo, which is called a closure.

There are also a variety of function closures.

function foo() {
	var a = 2;
	function baz() {
	console.log( a ); // 2
}
	bar( baz );
}
function bar(fn) {
	fn(); // 妈妈快看呀,这就是闭包!
}

Maybe after you understand it, the closure is just a slightly strange toy, but what I want to say is that the closure is not just a way of writing, and various situations are used in daily life:

function wait(message) {
	setTimeout( function timer() {
		console.log( message );
	}, 1000 );
}
wait( "Hello, closure!" );

The timer's internal scope does not disappear after 1000 milliseconds, and then contains a reference to the message.

2. Loops and closures

for (var i=1; i<=5; i++) {
	setTimeout( function timer() {
		console.log( i );
	}, i*1000 );
}

In my other little knowledge point on the front end, I mentioned that there is a variable promotion here, and it will print 6 every time. A little explanation, because after the function is delayed, I will go to the RHS search for the reference of i. i = 6, we originally wanted to capture a copy of i at each iteration, but each iteration is a shared scope, so all we find is 6;
if we modify the code by adding the principle of scope, Let's try:

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

Is this okay? Ha ha ha ha, still not work, because our lexical scope is empty, we need to establish a private attribute for him.

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

This is fine, because i points to the internal scope j of each internal anonymous function!
Beautify this code:

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

Of course, if you want to complete the logic more concisely, you can use let

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

Module

After understanding closures, let's understand how to use closures in general.

function Car() {
	var name = "五菱宏光";
	var age = "2 年";	

	function sayName () {
		console.log(name);
	}

	function sayAge () {
		console.log(age);
	}
	function drive () {
		console.log('drived');
    }
    
    return {
        sayName: sayName,
        sayAge: sayAge,
        drive: drive
    }
}

var car = Car();
car.sayName();

This is the use of modules.
Source of ideas for this blog: (NEW) [美] -Kyle-Simpson-JavaScript you do n’t know (Volume 1)

Published 20 original articles · won praise 5 · Views 2075

Guess you like

Origin blog.csdn.net/qq_42859887/article/details/105348870