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
  • 7,111
  • 18
  • 59
  • 98
  • It's not working, what could I be doing wrong? – rubixibuc Mar 15 '12 at 08:51
  • `document.getElementById` is a **host** function. Native functions are the built–ins (like Array, Object, etc.) and any function created by ECMAScript code (e.g. `function foo(){...}`, `var bar = function(){...}`). – RobG Mar 15 '12 at 08:53
  • 1
    possible duplicate of [JavaScript function aliasing doesn't seem to work](http://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work) – Shadow The GPT Wizard Mar 15 '12 at 08:54
  • Live test case with the `apply` workaround: http://jsfiddle.net/N4Ghd/ – Shadow The GPT Wizard Mar 15 '12 at 08:58

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
  • 54,081
  • 14
  • 89
  • 103
  • 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
  • 34,448
  • 50
  • 182
  • 322
Tom
  • 4,096
  • 2
  • 24
  • 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
  • 321,842
  • 108
  • 597
  • 820
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
  • 142,382
  • 31
  • 172
  • 209