[Greasemonkey] Javascript lexical scoping question

Jeremy Dunck jdunck at gmail.com
Thu Apr 14 23:17:13 EDT 2005


On 4/14/05, Julien Couvreur <julien.couvreur at gmail.com> wrote:
> General javascript question not specific to GM.
> 
> In the javascript shell:
> 
> > function test() { var internal = 5; this.visible = 6; }
> > props(test);
> --> expected: I thought no fields would be listed
> --> actual: lists "internal" as one of the fields, but not "visible"
> 
> > props(new test());
> --> only lists "visible", which is what I expected
> 
> I've been trying to clarify my understanding of javascript objects,
> scopes and closures, but I don't understand why "internal" is visible
> in the first test.

Well, I can't answer your actual question (why a var'd variable in a
function shows up as a field on the function's prototype), but here're
some things that might help understand scoping...

function test() { var internal = 5; this.visible = 6}
props(new test())
>>Fields: visible

In which case, internal is a variable scoped to the function test,
while this.visible is a variable assigned to the context created by
the new keyword.

"new" creates a new scoping context; that's the only thing that makes
a "constructor" function different from any other function.

As proof, notice this result:
test()
window.visible
>>6

So without the "new" keyword, the assignment of 6 to this.visible is
actual set on the window (global) object.

(Slightly) more details: the "new" keyword calls an internal function
named [[Construct]] which initializes a new Object, sets the prototype
for the new object to the prototype of the called function, and then
sets the "this" value for the called function to the newly constructed
object.  The called function just blissfully does its thing with
"this" or {name:value} or even this[name]=value.

The ECMAScript standard is pretty opaque, but also pretty thorough.  
http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf

I've never read it all. ;-)


More information about the Greasemonkey mailing list