首页 > 解决方案 > 与返回语句混淆

问题描述

我正在尝试使用 return 语句调用或调用函数,首先我编写return函数名,然后是括号,我们可以使用它return来返回函数的引用,但是如果不是,我可以使用语句调用函数,return那为什么?下面是我想要执行的代码

function make() {
  var count = 0;

  function counter() {
    count = count + 1;
    return count;
  }
  // here i ma calling a function with return statement return functionname followed by paranthesis
  return counter()
}
var result = make();
console.log(result());
console.log(result())
console.log(result())

标签: javascript

解决方案


您使用闭包count,您需要将函数引用返回到内部函数。

稍后调用此函数并从返回实际计数counter

function make() {
    function counter() {
        count = count + 1;
        return count;
    }

    var count = 0;
    return counter;
}

var result = make();

console.log(result());
console.log(result());
console.log(result());


推荐阅读