Is it okay to use with()?

后端 未结 3 1950
天命终不由人
天命终不由人 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.

提交回复
热议问题