使用闭包和自调用功能进行计数器 [英] Making counter using closure and self-invoking function

查看:89
本文介绍了使用闭包和自调用功能进行计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这段代码不起作用,

I'm wondering why this code doesn't work,

var uniqueInteger = function() {
    var counter = 0;
    return function() { return counter++; }
};

console.log(uniqueInteger()());  // 0
console.log(uniqueInteger()());  // 0
console.log(uniqueInteger()());  // 0 
console.log(uniqueInteger()());  // 0

,此代码即可。唯一的区别是使函数自调用,而不是在console.log()中调用它。p>

and this code does. The only difference is making the function self invoked instead of invoking it in console.log()

var uniqueInteger = (function() {
    var counter = 0;
    return function() { return counter++; }
}());

console.log(uniqueInteger());  // 0
console.log(uniqueInteger());  // 1
console.log(uniqueInteger());  // 2 
console.log(uniqueInteger());  // 3

我对JS很陌生,所以请原谅。谢谢!

I'm very new to JS so please excuse my noobness. Thanks!

推荐答案

第二个代码使用 var counter = 0 仅一次,因为在定义uniqueInteger时,它调用了一个函数,该函数返回完成初始化的函数。每次调用时,第一个代码都会创建 var counter = 0

The second code created a closure with var counter = 0 only once since when defining uniqueInteger, it called a function that returned a function where initialization is done. The first code creates var counter = 0 every time you call it.

请注意,使用第一个代码,您可以做:

Note that with the first code you can do:

ui = uniqueInteger();
console.log(ui()); // 0
console.log(ui()); // 1
ui2 = uniqueInteger();
console.log(ui()); // 2
console.log(ui2()); // 0
console.log(ui()); // 3
console.log(ui2()); // 1

这篇关于使用闭包和自调用功能进行计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆