language features - Are there legitimate uses for JavaScript's "with" statement? -
alan storm's comments in response answer regarding with
statement got me thinking. i've seldom found reason use particular language feature, , had never given thought how might cause trouble. now, i'm curious how might make effective use of with
, while avoiding pitfalls.
where have found with
statement useful?
another use occurred me today, searched web excitedly , found existing mention of it: defining variables inside block scope.
background
javascript, in spite of superficial resemblance c , c++, not scope variables block defined in:
var name = "joe"; if ( true ) { var name = "jack"; } // name contains "jack"
declaring closure in loop common task can lead errors:
for (var i=0; i<3; ++i) { var num = i; settimeout(function() { alert(num); }, 10); }
because loop not introduce new scope, same num
- value of 2
- shared 3 functions.
a new scope: let
, with
with introduction of let
statement in es6, becomes easy introduce new scope when necessary avoid these problems:
// variables introduced in statement // scoped each iteration of loop (let i=0; i<3; ++i) { settimeout(function() { alert(i); }, 10); }
or even:
for (var i=0; i<3; ++i) { // variables introduced in statement // scoped block containing it. let num = i; settimeout(function() { alert(num); }, 10); }
until es6 universally available, use remains limited newest browsers , developers willing use transpilers. however, can simulate behavior using with
:
for (var i=0; i<3; ++i) { // object members introduced in statement // scoped block following it. ({num: i}) { settimeout(function() { alert(num); }, 10); } }
the loop works intended, creating 3 separate variables values 0 2. note variables declared within block not scoped it, unlike behavior of blocks in c++ (in c, variables must declared @ start of block, in way similar). behavior quite similar let
block syntax introduced in earlier versions of mozilla browsers, not adopted elsewhere.
Comments
Post a Comment