[Greasemonkey] Can anybody explain to me the strange namespace
rule?
Lenny Domnitser
ldrhcp at gmail.com
Tue Jun 6 14:12:17 EDT 2006
On 6/5/06, Linan Wang <tali.wang+maillist at gmail.com> wrote:
> a.href='javascript:self_defined_function()';
In a case like this, you are better off not using unsafeWindow. Instead, use:
a.addEventListener('click', self_defined_function, false);
In case you really do need unsafeWindow for some reason, I'll try to
answer your question:
> 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?
A feature of Javascript is "closures". This means that the scope of
any function is the scope it is defined in, not where it executes. So
if you define a function in the Greasemonkey sandbox and then attach
it to unsafeWindow, it keeps its scope of the sandbox, and can access
other objects in that scope. Here is another example of a closure that
will hopefully make the concept clearer:
function giveMeAnotherFunction() {
var x = 5;
return function() {
return x;
}
}
var anotherFunction = giveMeAnotherFunction();
var y = anotherFunction();
anotherFunction is defined in a scope that includes the variable x,
but is called in a scope that does not.
Hope that helped.
More information about the Greasemonkey
mailing list