Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use with()?

Tags:

javascript

Once, I saw an example like this:

var a, x, y;
var r = 10;
with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

And it looks very convenience, because that way I don't have to type all the Math.s.

But when I take a look at the MDN, it says:

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.

So is it okay to use with()? In HTML5?

like image 524
Derek 朕會功夫 Avatar asked Jan 18 '23 02:01

Derek 朕會功夫


2 Answers

The MDN you linked says Using with is not recommended...
with is an excellent way of making spaghetti code for lunch.

You might like it, but the guy that will need to debug it will curse you.

javascript has some very weird operators, like the comma operator(,).
Can you understand what the following code does?

var a = "a";
var b = "b";
a = [b][b = a,0];

Well it swaps a and b... You don't understand , so as the guy that will need maintain your with code. Don't use hacks, hacks are cool in charades games, not in real code.


When is the comma operator useful?
The comma swap Fiddle

like image 77
gdoron is supporting Monica Avatar answered Jan 25 '23 20:01

gdoron is supporting Monica


It is okay to use any feature of JavaScript, so long as you understand it.

For example, using with you can access existing properties of an object, but you cannot create new ones.

Observe:

var obj = {a:1,b:2};
with(obj) {
    a = 3;
    c = 5;
}
// obj is now {a:3,b:2}, and there is a global variable c with the value 5

It can be useful for shortening code, such as:

with(elem.parentNode.children[elem.parentNode.children.length-3].lastChild.style) {
    backgroundColor = "red";
    color = "white";
    fontWeight = "bold";
}

Because the properties of the style object already exist.

I hope this explanation is clear enough.

like image 38
Niet the Dark Absol Avatar answered Jan 25 '23 20:01

Niet the Dark Absol