[Greasemonkey] Can anybody explain to me the strange namespace
rule?
Jeremy Dunck
jdunck at gmail.com
Tue Jun 6 12:04:38 EDT 2006
On 6/5/06, Linan Wang <tali.wang+maillist at gmail.com> wrote:
> unsafeWindow.self_defined_function=function(){
> another_function();
> };
>
> function another_function(){}
>
> It is understandable, but in the 'self_defined_function', if i want to call
> another function defined in userscript, that function should NOT be hooked
> into unsafe. Why? Can anybody explain to me?
This is how Javascript works. :)
But seriously, functions define lexical scopes, and when you define
the anonymous function assigned to self_defined_function, its scope
chain climbs into GM's sandbox global object, which is the objec that
another_function is defined on.
Any time you refer to a variable, it is resolved by inspecting the
current scope and, failing to find it there, by climbing the scope
chain until the reference is resolved or the chain runs out.
Additionally, these two bits are (almost) the same, functionally):
window.another_function = function() {}
...and...
function another_function() {}
In both cases, because the window variable refers to the global
object, you're assigning an attribute named "another_function" on that
global object.
So, when self_defined_function isn't found locally, it climbs up the
chain (to the GM global, which is -not- the page global for security
reasons). There it finds another_function.
More information about the Greasemonkey
mailing list