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

后端 未结 30 1793
伪装坚强ぢ
伪装坚强ぢ 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:15

    The with statement can be used to decrease the code size or for private class members, example:

    // demo class framework
    var Class= function(name, o) {
       var c=function(){};
       if( o.hasOwnProperty("constructor") ) {
           c= o.constructor;
       }
       delete o["constructor"];
       delete o["prototype"];
       c.prototype= {};
       for( var k in o ) c.prototype[k]= o[k];
       c.scope= Class.scope;
       c.scope.Class= c;
       c.Name= name;
       return c;
    }
    Class.newScope= function() {
        Class.scope= {};
        Class.scope.Scope= Class.scope;
        return Class.scope;
    }
    
    // create a new class
    with( Class.newScope() ) {
       window.Foo= Class("Foo",{
          test: function() {
              alert( Class.Name );
          }
       });
    }
    (new Foo()).test();
    

    The with-statement is very usefull if you want to modify the scope, what is necessary for having your own global scope that you can manipulate at runtime. You can put constants on it or certain helper functions often used like e.g. "toUpper", "toLower" or "isNumber", "clipNumber" aso..

    About the bad performance I read that often: Scoping a function won't have any impact on the performance, in fact in my FF a scoped function runs faster then an unscoped:

    var o={x: 5},r, fnRAW= function(a,b){ return a*b; }, fnScoped, s, e, i;
    with( o ) {
        fnScoped= function(a,b){ return a*b; };
    }
    
    s= Date.now();
    r= 0;
    for( i=0; i < 1000000; i++ ) {
        r+= fnRAW(i,i);
    }
    e= Date.now();
    console.log( (e-s)+"ms" );
    
    s= Date.now();
    r= 0;
    for( i=0; i < 1000000; i++ ) {
        r+= fnScoped(i,i);
    }
    e= Date.now();
    console.log( (e-s)+"ms" );
    

    So in the above mentioned way used the with-statement has no negative effect on performance, but a good one as it deceases the code size, what impacts the memory usage on mobile devices.

提交回复
热议问题