搜索
写经验 领红包
 > 育儿

在javascipt函数中闭包函数的作用(js闭包的作用域)

导语:JavaScript中函数和闭包的一些特性

JavaScript是世界上最流行的语言之一。继续阅读以更好地了解运行Web的语言。

尽管JavaScript是一种面向对象的语言,但在某些方面它与Java之类的其他OOP语言不同。因此,了解JavaScript的基本原则对Web开发人员至关重要。今天我们将通过一些示例代码来查看函数和闭包可以构成的一些陷阱。

function testVar(){

var x = 5;

console.log('first x is '+ x);//expected output 5

if (x == 5){

var x = 6;

console.log('second x is '+ x);// expected output 6

}

console.log('third x is '+ x);// expected output 6

}

testVar();

在这个函数中,x在最开始时被声明为5,所以毫无疑问它将在第3行中输出为5.在条件语句中,x被替换为6因为它满足条件因此第二个x是6同样,第8行将输出6,因为x在语句之外运行时已经被更改。现在让我们检查第二个例子。

function testFunction(){

console.log('first');

var printer = function(){

console.log('hello');

}

console.log('second');

var result = printer();

console.log('third');

console.log('result is '+ result);

}

testFunction();

输出顺序如下:

2 first

6 second

4 hello

8 third

9 result is undefined

'hello'之前没有打印'second'的原因是第3行和第4行只是声明打印机是一个功能,但不要调用它。结果是未定义的,而不是在第9行中打印'hello'; 这是因为变量结果等于函数 printer()。该函数 printer() 不声明任何返回值,因此方法控制台采用未定义的所有函数类型的默认值。

JavaScript中的闭包

function testClosure(){

var array = [];

for (var i=0; i<4; i++){

array[i] = function(){

return i;};

}

console.log(array[0]());//4

console.log(array[1]());//4

console.log(array[2]());//4

console.log(array[3]());//4

}

testClosure();

那么,这个函数的输出应该是1,2,3,4,对吧?实际上,实际输出都是4.但为什么会这样呢?

我们知道,当你创建一个函数时,它不会在你没有调用它时运行。所以,我们可以解决循环内部的内部函数,如下所示:

array[0] = function(){

return i;

};

array[1] = function(){

return i;

};

array[2] = function(){

return i;

};

array[3] = function(){

return i;

}

console.log(i);//3

这里的陷阱很难识别:为什么返回值仍然i不是数字?这是因为,此时,没有调用任何函数,并且i当循环结束时,第13行的输出为3。

因此,当调用函数一样array[0](),array[1](),array[2](),array[3](),返回值这里会i,这是4,因为i++意味着,下一次i出现i将增加1,它是存储在外部功能testClosure。

实际上,闭包的概念并不难理解。只需记住每个有资格访问另一个函数中的变量的函数称为闭包。

本文内容由小森整理编辑!