嵌套作用域
JavaScript 不仅区分全局和局部绑定。 块和函数可以在其他块和函数内部创建,产生多层局部环境。
例如,这个函数(输出制作一批鹰嘴豆泥所需的配料)的内部有另一个函数:
const hummus = function(factor) {const ingredient = function(amount, unit, name) {let ingredientAmount = amount * factor;if (ingredientAmount > 1) {unit += "s";}console.log(`${ingredientAmount} ${unit} ${name}`);};ingredient(1, "can", "chickpeas");ingredient(0.25, "cup", "tahini");ingredient(0.25, "cup", "lemon juice");ingredient(1, "clove", "garlic");ingredient(2, "tablespoon", "olive oil");ingredient(0.5, "teaspoon", "cumin");};
ingredient函数中的代码,可以从外部函数中看到factor绑定。 但是它的局部绑定,比如unit或ingredientAmount,在外层函数中是不可见的。
简而言之,每个局部作用域也可以看到所有包含它的局部作用域。 块内可见的绑定集,由这个块在程序文本中的位置决定。 每个局部作用域也可以看到包含它的所有局部作用域,并且所有作用域都可以看到全局作用域。 这种绑定可见性方法称为词法作用域。
