with语句

45 阅读1分钟

with语句:可以形成自己的作用域

// "use strict"; // with语句在严格模式下不建议使用

var message = "Hello World"
// console.log(message)

// with语句: 可以形成自己的作用域
var obj = {name: "why", age: 18, message: "obj message"}

function foo() {
  function bar() {
    with(obj) {
      console.log(message) // obj message
      console.log("------")
    }
  }
  bar()
}

foo()

var info = {name: "kobe"}
with(info) {
  console.log(name)
}

不建议使用with语句,因为它可能是混淆错误和兼容性问题的根源。