如何在javascript中使用“with”构造?

How to use “with” construction in javascript?

本问题已经有最佳答案,请猛点这里访问。

我有这个代码:

1
2
3
4
5
6
7
var home = {}
home.table={}
home.table.width = 100
home.table.length = 200
home.table.weight = 20
home.table.material ="wood"
home.table.color ="brown"

我怎样才能使用structure with (object) {code}来获得这样的东西?

1
2
3
4
5
6
7
8
9
var home = {}
with (home) {
table = {}
table.width = 100
table.length = 200
table.weight = 20
table.material ="wood"
table.color ="brown"
}


如果不指定对象,则无法在对象中创建属性。 首先创建属性,然后在with块中使用它:

1
2
3
4
5
6
7
8
9
var home = {};
home.table = {};
with(home) {
    table.width = 100;
    table.length = 200;
    table.weight = 20;
    table.material ="wood";
    table.color ="brown";
}

但不建议使用with。 它会使范围混乱,并且在HTML5严格模式下是不允许的。

您可以使用对象文字来创建具有更少代码的同一对象:

1
var home = { table: { width: 100, length: 200, weight: 20, material:"wood", color:"brown" } };

首先,您应该阅读此MDN页面。 从该页面引用:

Use of the with statement is not recommended, as it may be the source
of confusing bugs and compatibility issues. See the"Ambiguity Con"
paragraph in the"Description" section below for details.

并且:

Using with is not recommended, and is forbidden in ECMAScript 5 strict
mode. The recommended alternative is to assign the object whose
properties you want to access to a temporary variable.

其次,如果我正在编写代码,我会这样做:

1
2
3
4
5
6
7
8
var home = {};
home.table = {
    width: 100,
    length: 200,
    weight: 20,
    material: 20,
    color:"brown"
};

或者,整个事情甚至可以在一个JS文字中完成:

1
2
3
4
5
6
7
8
9
var home = {
  table: {
    width: 100,
    length: 200,
    weight: 20,
    material: 20,
    color:"brown"
  }
};

这是一个使用临时变量的例子(建议用MDN代替with)就是这样 - 虽然在这种情况下我更喜欢上面的格式:

1
2
3
4
5
6
7
8
var home = {};
home.table = {};
var table = home.table;
table.width = 100;
table.length = 200;
table.weight = 20;
table.material = 20;
table.color ="brown";