Home >Web Front-end >JS Tutorial >Closure analysis of javascript learning_javascript skills
In ECMAScript, all variables declared at the function declaration and seen outside the function can access their final values inside the function!
The closure function can only access the final value of the variable!!!
eg:
function fnTest(arr) {
for (var i=0;i < arr.length;i ) {
arr[i]=function () { alert(i " | " arr[i]); };
}
}
var arr = [0,1,2,3];
fnTest(arr);
for (var i=0; i < arr.length;i ) {
arr[i](); //Always output 4 and there is an undefinedBecause after the function exits, the i value is 4, so the accessed value is only 4
//The result will pop up 4 consecutive "4|undefined"
}
Not only can you access the variable value outside the closure in the closure, but you can also set its value
eg:
function fnTest() {
var a="June";
return {
set:function (param) {a = param},
get:function () {return a}
};
}
var obj = fnTest();
alert(obj.get());//Pop up June
obj.set(586);
alert(obj.get());//pop up 586