Javascript闭包和范围之谜

Javascript closure and scope riddle

本文关键字:范围 闭包 Javascript      更新时间:2023-09-26

我听到了这个问题,我不确定如何解决它。

要求是:实现函数from,以便在以下场景中像这样执行:

var x = from(3);
console.log(x()); //outputs 3
console.log(x()); //outputs 4
//TODO: implement from()

我尝试了类似的东西:

function from(val) {
  var counter = val;
  return function(){
    return counter+=1;
  }
}

但是当我第一次运行它时,它会增加值,所以这是不行的。

var x = from(3);
function from(startValue) {
   var counter = startValue;
   return function() {
     return counter++;
   }
}
console.log(x()); //outputs 3
console.log(x()); //outputs 4

最直接的解决方案是简单地从counter中减去1

function from(val) {
    var counter = val - 1;
    return function(){
        return counter += 1;
    }
}

但是,在这种情况下,您可以使用后缀++运算符,因为在 counter++ 中,counter 的值增加 1,但返回旧的 counter 值。
你应该很高兴

function from(val) {
    var counter = val;
    return function(){
        return counter++;
    }
}

为了完整起见,等效于counter += 1 将是 ++counter

function from(val) {
  var counter = val;
  return function() {
    return counter++;
  }
}
var x = from(3);
alert(x()); //outputs 3
alert(x()); //outputs 4
alert(x()); //outputs 5
alert(x()); //outputs 6
alert(x()); //outputs 7
alert(x()); //outputs 8

试试这个