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/

5
  • possible duplicate of JavaScript function aliasing doesn't seem to work Commented Feb 6, 2011 at 23:13
  • Have you tried, g.call(document, 'sampleID'); ?? Commented Feb 6, 2011 at 23:16
  • @Pointy No, I didn't think ahead :) Commented Feb 6, 2011 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. Commented Feb 6, 2011 at 23:36
  • @Šime yeah, absolutely! Your example is way better than the one in the other question, do keep this around. Commented Feb 6, 2011 at 23:37

1 Answer 1

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');  
}
Sign up to request clarification or add additional context in comments.

3 Comments

+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: 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).
@Tim Yes, that would be the more reasonable way to go.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.