Is it okay to use with()?

后端 未结 3 1951
天命终不由人
天命终不由人 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:42

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-19 11:56

    In his excellent book "Javascript: The Good Parts", Douglas Crockford lists the "with Statement" in Appendix B: The Bad Parts.

    He says "Unfortunately its results can sometimes be unpredictable, so it should be avoided".

    He goes on to give an example, where an assignment inside the with will operate on different variables depending on whether the object is defined or not.

    See With statement considered harmful (but less detailed than the explanation in the book).

    0 讨论(0)
提交回复
热议问题