[Greasemonkey] Adding methods/properies to document object with GM

Lenny Domnitser ldrhcp at gmail.com
Wed Jul 20 17:10:12 EDT 2005


On 7/20/05, Blake West <blakewest at gmail.com> wrote:
> Well, I don't understand the scope issue

Consider this:

makeMultiplier(x) {
  function multiplyByX(y) {
    return y * x;
  }
  return multiplier;
}
var myMultiplier = makeMultiplier(4);
alert(myMultiplier(3)); // alerts 12
alert(myMultiplier(5)); // alerts 15

When you call myMultiplier, you specify the variable y, but x does not
exist where you call myMultiplier. The reason this works is that x
exists where myMultiplier is defined (as multiplyByX).

Now, apply this to what you are doing with the DOM. Pretend the user
script is the makeMultiplier function, and the function you are
defining is the multiplyByX function. The onload of your link is a
Javascript function, like any other. When you write "onload=..." in
the HTML, it is defined outside of the user script. It is like making
the multiplier outside of makeMultiplier, which would fail, because x
is not defined. When you define onload from the user script, you have
all of the objects in the user script available to you.

I hope that made sense. This is definitely something worth
understanding, since a lot of problems I've run into writing user
scripts involve scope, particularly when using timers and events.


More information about the Greasemonkey mailing list