有些语句可以在作用域链的前端临时添加一个变量对象,该变量对象会在代码执行后被移除。

当执行流进入下列任意一个语句时,作用域链就会得到加长。

  • try-catch 语句的 catch 块

  • with 语句

用 with 语句延长作用域链

with 语句可以将指定的对象添加到作用域链中。下面这个例子,体现了 with 语句延长作用域链的效果。

  1. class testClass {
  2. constructor() {
  3. this.color = 'red'
  4. }
  5. }
  6. const testFunction = () => {
  7. const testObject = new testClass
  8. with(testObject) {
  9. console.log('color:', color) // color: red
  10. }
  11. console.log('color:', color) // color is not defined
  12. }
  13. testFunction()

上面这个例子中,我们定义了 testClass 这个类。并在 testFunction 中对 testClass 这个类进行实例化。

第 10 行代码,在 with 语句接收了 testObject 对象,因此 testObject 的变量对象(包含了 testObject 中的 color 属性)会被临时添加到作用域的前端。此时 with 语句中可以访问 color 变量。

第 14 行代码,当在 with 外,再次打印 color 变量的时候,会直接报错,并且提示 color 没有定义,因为在作用域链中,并没有 color 这个变量。