This article brings you the explanation of closures in js and examples (code) of variable declarations in advance. It has certain reference value. Friends in need can refer to it. Hope it helps.
Closure
Function B is declared in function A, and function B uses variables in the scope of function A, and Function A returns function B, then function B forms a closure on the scope of function A. After function A is called, as long as the returned function B exists, the scope of function A will always exist
function makeFn(){ var n1 = 100; function fn(){ var n2 = 200; console.log(n1); } return fn; } var f2 = makeFn(); f2();
Closure can realize the private properties of the object, such as:
var obj = { name:"sunset", age:12, speak:function(){ console.log("我是"+this.name); } } console.log(obj.name);
Another example:
function makeObj(){ var name = "sunset"; var age = 12; var obj = { speak:function(){ console.log("我叫"+name); } } return obj; } console.log(obj.speak());
The last very good example: (import jQuery and execute it to see)
<script> for (var i = 0; i < 10; i++) { function makeFn(index) { function fn() { console.log(index) } return fn; } var btn = makeFn(i); $("<button></button>") .text(i + 1) .appendTo(document.body) .on("click",btn) } </script>
Variable declaration in advance:
In the scope of js, all variable declarations will be advanced, but assignment will not be advanced (variables will not be demonstrated in advance, learn This needs no explanation)
var a = 3; function f1(){ console.log(a); var a = 10; } f1();
is equivalent to
function f1(){ var a; console.log(a); a = 10; } f1();
Related recommendations:
Detailed explanation of JS variable declaration
##JavaScript closure-variables and this object in the closure
The above is the detailed content of Explanation of closures in js and examples of variable declaration in advance (code). For more information, please follow other related articles on the PHP Chinese website!