Javascript - 无法理解关闭

时间:2015-10-29 18:20:19

标签: javascript scope closures chain

我有以下代码:

function bird(type) {
    return function (whattosay) { //return the whole function
        console.log (type + ' ' + whattosay)
    }

}

var birdRef = bird('blackbird'); 
birdRef('singing in the dead of night');

var secondRef = bird('whitebird');

birdRef('singing after that night');

我试图熟悉两个概念,闭包和范围链。 好吧,在我的第一个birdRef我得到一个新的函数对象,然后我在该行后调用它。最后,我看到黑夜在黑暗中唱歌"在控制台中。我明白为了找到鸟类型var,闭包给你一个对父类的引用,它有点在范围链中寻找那个var并最终找到它,所以我们看到了鸟的类型

那么你有这个:

var secondRef = bird('whitebird');

已经传递了一个新参数,所以现在var"类型"鸟类功能从黑鸟变为白鸟。

现在我回到我之前创建的函数birdRef,我不明白的是,接下来会发生什么:

birdRef('singing after that night');

我得到"黑鸟在那天晚上唱歌"而不是白鸟。好吧,如果我没有弄错的话,birdRef函数没有找到它的父函数鸟,并且读取更新的鸟类变量的类型(我的意思是他无法找到它var在本地环境中,所以他查看外部环境并找到var" type")?

很抱歉,如果我对此不熟悉,那么感谢你没有多大意义,谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

第二次实际调用第一个闭包的结果。

以下一行:

birdRef('singing after that night');

应该是:

secondRef('singing after that night');

我在下面提供了一个工作演示。



function bird(type) {
    return function (whattosay) { //return the whole function
        console.log (type + ' ' + whattosay)
    }

}

var birdRef = bird('blackbird'); 
birdRef('singing in the dead of night');

var secondRef = bird('whitebird');
secondRef('singing after that night');
// ^^ secondRef instead of birdRef

// Test is again.
birdRef('singing in the dead of night');
secondRef('singing after that night');




因为type是在函数调用的词法范围内定义的,所以它不能在该词法范围之外访问。如上所示,除非在定义变量的词法范围内修改变量,否则无法访问或修改变量。