2

I have this code:

var home = {}
home.table={}
home.table.width = 100
home.table.length = 200
home.table.weight = 20
home.table.material = "wood"
home.table.color = "brown"

How can I use structure with (object) {code} right to get something like this?

var home = {}
with (home) {
table = {}
table.width = 100
table.length = 200
table.weight = 20
table.material = "wood"
table.color = "brown"
}
Orange Fox
  • 147
  • 7

2 Answers2

2

First off, you should read this MDN page. Quoting from that page:

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.

and also:

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.


Secondly, if I were writing your code, I would do it like this:

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

or, the whole thing can even be done in one JS literal:

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

Here's an example using a temporary variable (as recommended as a substitute for with by MDN) would be this - though in this case I would prefer the above format:

var home = {};
home.table = {};
var table = home.table;
table.width = 100;
table.length = 200;
table.weight = 20;
table.material = 20;
table.color = "brown";
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Why not `var home = { table : { width : 100, length : 200 } };` ? – Tibos Feb 01 '14 at 18:47
  • @OrangeFox - temporary variable example added to my answer, though in this case, I would prefer the one above it. – jfriend00 Feb 01 '14 at 18:55
  • 1
    @Tibos - if you want max brevity, you can certainly nest the definition like that all in one JS literal. Sometimes that is appropriate, sometimes it is not as readable - it depends upon context not provided here. My aim here was to answer the question about alternatives to using using of `with` which only has to do with the declaration of the table object. – jfriend00 Feb 01 '14 at 18:59
2

You can't create properties in an object without specifying the object. Create the property first, then you can use it inside the with block:

var home = {};
home.table = {};
with(home) {
    table.width = 100;
    table.length = 200;
    table.weight = 20;
    table.material = "wood";
    table.color = "brown";
}

Using with is not recommended, though. It makes for confusing scope, and is disallowed in HTML5 strict mode.

You can use object literals to create the same object with even less code:

var home = { table: { width: 100, length: 200, weight: 20, material: "wood", color: "brown" } };
Guffa
  • 687,336
  • 108
  • 737
  • 1,005