Are there legitimate uses for JavaScript's “with” statement?

后端 未结 30 2140
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:22

Alan Storm\'s comments in response to my answer regarding the with statement got me thinking. I\'ve seldom found a reason to use this particular language feature, and had ne

30条回答
  •  故里飘歌
    2020-11-22 05:25

    As Andy E pointed out in the comments of Shog9's answer, this potentially-unexpected behavior occurs when using with with an object literal:

    for (var i = 0; i < 3; i++) {
      function toString() {
        return 'a';
      }
      with ({num: i}) {
        setTimeout(function() { console.log(num); }, 10);
        console.log(toString()); // prints "[object Object]"
      }
    }
    

    Not that unexpected behavior wasn't already a hallmark of with.

    If you really still want to use this technique, at least use an object with a null prototype.

    function scope(o) {
      var ret = Object.create(null);
      if (typeof o !== 'object') return ret;
      Object.keys(o).forEach(function (key) {
        ret[key] = o[key];
      });
      return ret;
    }
    
    for (var i = 0; i < 3; i++) {
      function toString() {
        return 'a';
      }
      with (scope({num: i})) {
        setTimeout(function() { console.log(num); }, 10);
        console.log(toString()); // prints "a"
      }
    }
    

    But this will only work in ES5+. Also don't use with.

提交回复
热议问题