2

I have written this code (this is a snippet) that doesn't seem to be working. I have isolated it to here.

grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]

Is it possible to create references to native function in javascript. I am doing something with the grabbed element, I just left it out for example. The grab function doesn't seem to work.

I am using FireFox's most recent version

rubixibuc
  • 6,434
  • 18
  • 51
  • 89

4 Answers4

3

The way you're doing it will mess up the assignment of the this value for the function.

grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]

here this will be the global object. Try:

grab.apply(window.document, ["blueBox"])

or in newer browsers:

grab = window.document.getElementById.bind(window.document);

to get directly define what this will be.

Yoshi
  • 53,111
  • 13
  • 85
  • 102
  • 1
    @Yoshi—Nothing whatever to do with scope, everything to do with the function's *this* keyword. – RobG Mar 15 '12 at 09:13
  • @RobG You're correct, it's a very bad habit of mine to always mix the wording when trying to explain it. ;) – Yoshi Mar 15 '12 at 09:17
1
function grab(id) {
    return window.document.getElementById(id);
}

grab("blueBox");
BenMorel
  • 31,815
  • 47
  • 169
  • 296
Tom
  • 4,056
  • 2
  • 23
  • 38
1

The first step here is always the JavaScript console. Firebug is your friend. Tell us the error message if it doesn't mean anything to you.

In the mean time, here is a workaround:

var grab = function(id) { return window.document.getElementById(id); }
Aaron Digulla
  • 310,263
  • 103
  • 579
  • 794
0

The reason is because the function getElementById is not being called as a method of document, so its this keyword doesn't reference the right object. Using call as suggested in other answers shows that when this references the document, getElementById works.

RobG
  • 134,457
  • 30
  • 163
  • 204