Is it okay to use with()?

后端 未结 3 2175
天命终不由人
天命终不由人 2021-01-19 10:51

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

3条回答
  •  情书的邮戳
    2021-01-19 11:46

    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

提交回复
热议问题