6

Possible Duplicate:
JavaScript function aliasing doesn't seem to work

Why doesn't this work?

function foo() {

    var g = document.getElementById;

    g('sampleID');

} 

This error is thrown in Chrome: Uncaught TypeError: Illegal invocation
... and in Firefox: Error: uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object"

It works in IE9 beta though !!

Demo: http://jsfiddle.net/ugBpc/

Community
  • 1
  • 1
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • possible duplicate of [JavaScript function aliasing doesn't seem to work](http://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work) – Pekka Feb 06 '11 at 23:13
  • Have you tried, `g.call(document, 'sampleID');` ?? – Pointy Feb 06 '11 at 23:16
  • @Pointy No, I didn't think ahead :) – Šime Vidas Feb 06 '11 at 23:19
  • @Pekka I voted to close this. Is that OK? I don't want to delete it since I'm afraid that that would remove it from my list of questions, and I'd like to keep this question. – Šime Vidas Feb 06 '11 at 23:36
  • @Šime yeah, absolutely! Your example is *way* better than the one in the other question, do keep this around. – Pekka Feb 06 '11 at 23:37

1 Answers1

5

Most browsers require that the document.getElementById method is called in the context of the original object (document). So this would work:

function foo() {      
    var g = document.getElementById;      
    g.call(document, 'sampleID');  
}

This will fail in Internet Explorer 7 and lower, however, because DOM methods don't inherit from Function.prototype. Your original example should work in all versions of Internet Explorer.

You could also use Function.prototype.bind, in browsers that support it or where you have provided the compatibility implementation:

function foo() {      
    var g = document.getElementById.bind(document);      
    g('sampleID');  
}
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • +1. I'd advise against doing any of this though. If `document.getElementById()` is too long, just wrap it in a function with a shorter name rather than attempt to create a reference to a host method. – Tim Down Feb 06 '11 at 23:24
  • @Tim Down: agreed, I don't think it's necessary to use `bind` for something like this. I tested performance a while ago and it was orders of magnitude slower in Chrome and Firefox (although I'm not sure why). – Andy E Feb 06 '11 at 23:28
  • @Tim Yes, that would be the more reasonable way to go. – Šime Vidas Feb 06 '11 at 23:30