我正在尝试通过使用 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 才能通过此测试。但有人能解释一下为什么吗?
最佳答案
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);
});
关于javascript - 基本的 JavaScript 内嵌函数解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612423/