Tuesday, May 15, 2012

javascript : with Statement Considered Harmful


Mynotes :

with(obj) , adds the current object to the start of the current execution context's scope.
with(obj){
  x=10;
y=10;
z=10;
}
 if  the obj does not have a variable x as its property, x will be searched through the rest of the objects in scope and set if any x is found.
 Only if you are sure obj has x use with .

 Code A will rightly assign 11 to propery x of the object passed.
 However Code B will assign 11 to the global variable which is not intended.

Things are trivial here but i tried to emphasize what 'with' can do if not properly understood and used.

Code A
 <script>
            var x =10;
            with({x:10}){
                    x=11;
            }
            alert(x);
    </script>

 Code B
 <script>
            var x =10;
            with({y:10}){
                    x=11;
            }
            alert(x);
    </script>

 

with Statement Considered Harmful

April 11, 2006 at 7:52 am by Douglas Crockford | In Development | 64 Comments JavaScript’s with statement was intended to provide a shorthand for writing recurring accesses to objects. So instead of writing
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
You can write
with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
    bing = true;
    bang = true;
}
That looks a lot nicer. Except for one thing. There is no way that you can tell by looking at the code which bing and bang will get modifed. Will ooo.eee.oo.ah_ah.ting.tang.walla.walla be modified? Or will the global variables bing and bang get clobbered? It is impossible to know for sure.
The with statement adds the members of an object to the current scope. Only if there is a bing in ooo.eee.oo.ah_ah.ting.tang.walla.walla will ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing be accessed.
If you can’t read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.
Fortunately, JavaScript also provides a better alternative. We can simply define a var.
var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;
o.bing = true;
o.bang = true;
Now there is no ambiguity. We can have confidence that it is ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing and ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang that are being set, and not some hapless variables.

No comments:

Post a Comment