Home >Web Front-end >JS Tutorial >Closure analysis of javascript learning_javascript skills

Closure analysis of javascript learning_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:14:511115browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn