Web 前端

JavaScript with 语句

2021-01-05  本文已影响0人  时光觅迹

with 语句的作用是将代码的作用域设置到一个特定的对象中。语法:

with (expression) statement;

定义with语句的目的主要是为了简化多次编写同一个对象的工作。

在不使用 with 语句时,我们的代码可能是这样:

var obj = {
  name: 'jay',
  age: '18',
  phone: '130xxxxxxxx'
}

var objName = obj.name;
var objAge = obj.age;
var objPhone = obj.phone;

alert("my name is " + objName + ", i'm " + objAge + " years old, my phone number is " + objPhone + " !");

// 打印结果:my name is jay,  i'm 18 years old,  my phone number is 130xxxxxxxx !

这里要获得 obj 的属性时,需要多次写出 obj.xxx

同样获取 obj 的属性实现以上功能呢,我们再来看看使用 with 语句时怎么写:

var obj = {
  name: 'jay',
  age: '18',
  phone: '130xxxxxxxx'
}

with (obj) {
  alert("my name is " + name + ", i'm " + age + " years old, my phone number is " + phone + "!");
}

// 打印结果:my name is jay,  i'm 18 years old,  my phone number is 130xxxxxxxx !

这里可以看到,我们省去了许多 obj.xxx 这样的代码,我们的代码更为简洁。

我们使用 with 语句关联了 obj 对象,这意味着在 with 语句的代码块内部,每个变量首先被认为是一个局部变量,如果在局部环境中找不到该变量的定义,就会查询 obj 对象中事都有同名的属性,如果发现了同名属性,则以 obj 对象属性的值作为变量的值。

「注意」

  1. 严格模式下不允许使用 with 语句,否则将视为语法错误!
  2. 由于大量使用 with 语句会导致性能下降,同时也会给调试代码造成困难,因此在开发大型应用程序是,不建议使用 with 语句!
上一篇 下一篇

猜你喜欢

热点阅读