[Greasemonkey] Javascript lexical scoping question

Edward Lee edilee at gmail.com
Fri Apr 15 11:19:15 EDT 2005

On 4/15/05, Prakash Kailasa <pk-moz at kailasa.net> wrote:
> On Fri, Apr 15, 2005 at 01:54:22AM -0500, Edward Lee wrote:
> > Does anyone know why this was mentioned in the Statements section?
> > "The with statement should not be used." 
> I have googled for references to "with statement" being harmful, but
> all I could find was this site (www.crockford.com) only. 

Well, I looked through the other pages, and I suppose this is why.

"The with statement was intended to provide a shorthand in accessing
members in deeply nested objects. Unfortunately, it behaves very badly
when setting new members. Never use the with statement. Use a var

Normally accessing things should work fine inside the with statement,
but creating new members for that object is not possible without
referencing the object again.

> a = {"x": 0}
> with(a) { x = 1; var y = 2; z = 3; }
> props(a)
Fields: x

Note that y and z are both still set in that scope or global.

So as long as you're just getting/setting members that already exist,
"with" should work fine and be shorter than other notations. Typos
could be a big issue because if you try to assign an existing member a
value but give the wrong variable name, it'll create a new variable
(most likely in the global space).


More information about the Greasemonkey mailing list