基本的JavaScript嵌入式函数说明

时间:2014-09-01 20:14:23

标签: javascript testing jasmine mocha

我试图通过使用JavaScript Koans进行测试来学习JavaScript。我遇到过这段代码,我很难理解,也许有人可以教育我吗?

代码:

  it("should use lexical scoping to synthesise functions", function () {

    function makeMysteryFunction(makerValue)
    {
      var newFunction = function doMysteriousThing(param)
      {
        return makerValue + param;
      };
      return newFunction;
    }

    var mysteryFunction3 = makeMysteryFunction(3);
    var mysteryFunction5 = makeMysteryFunction(5);

    expect(mysteryFunction3(10) + mysteryFunction5(5)).toBe(FILL_ME_IN);
  });

所以" FILL_ME_IN"必须为23才能通过此测试。但有人可以解释我为什么?

1 个答案:

答案 0 :(得分:1)

makeMysteryFunction返回的函数是closure的示例。如果您要重写这样的代码,它可能更具可读性:

it("should use lexical scoping to synthesise functions", function () {

    // This function takes a number and returns a function
    function getAddingFunction(firstNumber){
        // The function it returns takes a *second* number and returns the sum of both numbers.
        // The function returned is an example of a 'closure' - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
        // This means it remembers the scope in which it was created and, therefore, the `firstNumber` variable.
        return function addNumbers(secondNumber){
            // The function remembers firstNumber from its creation, and takes secondNumber upon use.
            return firstNumber + secondNumber;
        };
    }

    var addTo3 = getAddingFunction(3); // Returns a function which remembers firstNumber = 3
    var addTo5 = getAddingFunction(5); // Returns a function which remembers firstNumber = 5

    expect(addTo3(10) + addTo5(5)).toBe(FILL_ME_IN);
});