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

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

    You got to see the validation of a form in javascript at W3schools http://www.w3schools.com/js/js_form_validation.asp where the object form is "scanned" through to find an input with name 'email'

    But i've modified it to get from ANY form all the fields validate as not empty, regardless of the name or quantity of field in a form. Well i've tested only text-fields.

    But the with() made things simpler. Here's the code:

    function validate_required(field)
    {
    with (field)
      {
      if (value==null||value=="")
        {
        alert('All fields are mandtory');return false;
        }
      else
        {
        return true;
        }
      }
    }
    
    function validate_form(thisform)
    {
    with (thisform)
      {
        for(fiie in elements){
            if (validate_required(elements[fiie])==false){
                elements[fiie].focus();
                elements[fiie].style.border='1px solid red';
                return false;
            } else {elements[fiie].style.border='1px solid #7F9DB9';}
        }
    
      }
      return false;
    }
    
    0 讨论(0)
  • 2020-11-22 05:16

    Having experience with Delphi, I would say that using with should be a last-resort size optimization, possibly performed by some kind of javascript minimizer algorithm with access to static code analysis to verify its safety.

    The scoping problems you can get into with liberal use of the with statement can be a royal pain in the a** and I wouldn't want anyone to experience a debugging session to figure out what the he.. is going on in your code, only to find out that it captured an object member or the wrong local variable, instead of your global or outer scope variable which you intended.

    The VB with statement is better, in that it needs the dots to disambiguate the scoping, but the Delphi with statement is a loaded gun with a hairtrigger, and it looks to me as though the javascript one is similar enough to warrant the same warning.

    0 讨论(0)
  • 2020-11-22 05:18

    You can define a small helper function to provide the benefits of with without the ambiguity:

    var with_ = function (obj, func) { func (obj); };
    
    with_ (object_name_here, function (_)
    {
        _.a = "foo";
        _.b = "bar";
    });
    
    0 讨论(0)
  • 2020-11-22 05:18

    You can use with to avoid having to explicitly manage arity when using require.js:

    var modules = requirejs.declare([{
        'App' : 'app/app'
    }]);
    
    require(modules.paths(), function() { with (modules.resolve(arguments)) {
        App.run();
    }});
    

    Implementation of requirejs.declare:

    requirejs.declare = function(dependencyPairs) {
        var pair;
        var dependencyKeys = [];
        var dependencyValues = [];
    
        for (var i=0, n=dependencyPairs.length; i<n; i++) {
            pair = dependencyPairs[i];
            for (var key in dependencyPairs[i]) {
                dependencyKeys.push(key);
                dependencyValues.push(pair[key]);
                break;
            }
        };
    
        return {
            paths : function() {
                return dependencyValues;
            },
    
            resolve : function(args) {
                var modules = {};
                for (var i=0, n=args.length; i<n; i++) {
                    modules[dependencyKeys[i]] = args[i];
                }
                return modules;
            }
        }   
    }
    
    0 讨论(0)
  • 2020-11-22 05:19

    For some short code pieces, I would like to use the trigonometric functions like sin, cos etc. in degree mode instead of in radiant mode. For this purpose, I use an AngularDegreeobject:

    AngularDegree = new function() {
    this.CONV = Math.PI / 180;
    this.sin = function(x) { return Math.sin( x * this.CONV ) };
    this.cos = function(x) { return Math.cos( x * this.CONV ) };
    this.tan = function(x) { return Math.tan( x * this.CONV ) };
    this.asin = function(x) { return Math.asin( x ) / this.CONV };
    this.acos = function(x) { return Math.acos( x ) / this.CONV };
    this.atan = function(x) { return Math.atan( x ) / this.CONV };
    this.atan2 = function(x,y) { return Math.atan2(x,y) / this.CONV };
    };
    

    Then I can use the trigonometric functions in degree mode without further language noise in a with block:

    function getAzimut(pol,pos) {
      ...
      var d = pos.lon - pol.lon;
      with(AngularDegree) {
        var z = atan2( sin(d), cos(pol.lat)*tan(pos.lat) - sin(pol.lat)*cos(d) );
        return z;
        }
      }
    

    This means: I use an object as a collection of functions, which I enable in a limited code region for direct access. I find this useful.

    0 讨论(0)
  • 2020-11-22 05:20

    I actually found the with statement to be incredibly useful recently. This technique never really occurred to me until I started my current project - a command line console written in JavaScript. I was trying to emulate the Firebug/WebKit console APIs where special commands can be entered into the console but they don't override any variables in the global scope. I thought of this when trying to overcome a problem I mentioned in the comments to Shog9's excellent answer.

    To achieve this effect, I used two with statements to "layer" a scope behind the global scope:

    with (consoleCommands) {
        with (window) {
            eval(expression); 
        }
    }
    

    The great thing about this technique is that, aside from the performance disadvantages, it doesn't suffer the usual fears of the with statement, because we're evaluating in the global scope anyway - there's no danger of variables outside our pseudo-scope from being modified.

    I was inspired to post this answer when, to my surprise, I managed to find the same technique used elsewhere - the Chromium source code!

    InjectedScript._evaluateOn = function(evalFunction, object, expression) {
        InjectedScript._ensureCommandLineAPIInstalled();
        // Surround the expression in with statements to inject our command line API so that
        // the window object properties still take more precedent than our API functions.
        expression = "with (window._inspectorCommandLineAPI) { with (window) { " + expression + " } }";
        return evalFunction.call(object, expression);
    }
    

    EDIT: Just checked the Firebug source, they chain 4 with statements together for even more layers. Crazy!

    const evalScript = "with (__win__.__scope__.vars) { with (__win__.__scope__.api) { with (__win__.__scope__.userVars) { with (__win__) {" +
        "try {" +
            "__win__.__scope__.callback(eval(__win__.__scope__.expr));" +
        "} catch (exc) {" +
            "__win__.__scope__.callback(exc, true);" +
        "}" +
    "}}}}";
    
    0 讨论(0)
提交回复
热议问题