Closure-caused bugs
function bug () {
var nums = [];
for (var i = 0; i < 3; i++) {
Nums[i] = function () {
return i;
};
}
return nums;
}
var nums_bug = bug ();
Console.log (Nums_bug[0] ());
Console.log (Nums_bug[1] ());
Console.log (Nums_bug[2] ());
Fix bugs
function Fbug () {
var nums = [];
for (var i = 0; i < 3; i++) {
Nums[i] = (function (i) {
return i;
}) (i);
}
return nums;
}
var nums = Fbug ();
Console.log (Nums);
Nums[0] (); 0
NUMS[1] (); 1
NUMS[2] (); 2
Isolation variable Scope
(function () {
var name = "Zs";
function A () {
name = ' SSS ';
}
})();
(function () {
var name = "ls";
function A () {
name = ' VVV ';
}
})();
Counter
Common implementation
var num = 0;
function Countnum () {
num + +;
}
Countnum ();
Console.log (num);
Closure implementation
var counter = (function () {
var counterper = 0;
return function () {
return counterper++;
}
})();
Console.log (counter ());
var counter= (function () {
Assigning an initial value
var count=0;
The closure is formed when externally called
return function () {
return count++;
}
})();
Declaring private variables
/*function people () {
THIS.name = ' Zhang San ';
}
var p = new people ();
Console.log (p.name); * *
Directly can. To access, which is the public attribute, the security is poor
The private property is passed through the. Unreachable
var people = (function () {
var name = ';
function people () {
}
People.prototype = {
Getname:function () {
return name;
},
Setname:function (newName) {
name = NewName;
}
}
return people;
})();
var p = new people ();
This
var test = ' John Doe ';
function Th_test () {
Console.log (this.test);
}
function Bth_test () {
var test = ' Harry ';
return function () {
Console.log (this.test);
}
}
This always points to the object that called it
JS Closed Package