【发布时间】:2013-07-11 23:55:04
【问题描述】:
通过 Javascript Koans 工作,我被以下代码挂断了:
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);
});
它得到 23,这很好。我感到困惑的是,赋予“mysteryFunction3”变量的参数如何/为什么作为“param”传递给 doMysteriousThing 函数。
如果有一个内部函数和一个外部函数,每个函数都有一个参数,那么在给定指定参数的情况下定义一个等于外部函数的变量,例如:
var mysteryFunction3 = makeMysterFunction(3);
将使其向外部函数的变量实例发送参数,例如:
mysteryFunction3(10)
会导致该参数 (10) 被读取为内部函数的参数吗?
【问题讨论】:
-
JavaScript 函数在最初定义它们的变量范围上形成一个闭包。
doMysteriousThing函数是在传递makerValue的变量范围内创建的。这使该函数能够引用makerValue,即使该函数已返回并分配给您的mysteryFunction3。如您所见,它在其返回值return makerValue + param;中使用它,其中makerValue再次被传递给makeMysteryFunction(),param被传递给doMysteriousThing() -
如果同一个函数没有 3 个不同的名称,可能不会那么混乱。
newFunction、doMysteriousThing和mysteryFunction3都指的是同一个函数。为了清理它,我会去掉newFunction和doMysteriousThing的名字,只做return function(param) { return makerValue + param; };