Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Referencing host function via local variable [duplicate]

Tags:

javascript

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/

like image 223
Šime Vidas Avatar asked Feb 06 '11 23:02

Šime Vidas


People also ask

Can you declare the same variable twice in JavaScript?

Here you can declare the same variables more than one time and can be updated. If you declare variable inside the block statement, the variable will leak outside.

What is $scope in JavaScript?

Scope determines the accessibility of variables, objects, and functions from different parts of the code.

Are functions reusable in JavaScript?

JavaScript supports user-defined functions, which is highly advantageous for developing a library of reusable code. You can place code you think you might reuse into one or more functions and save those functions in a text file for future reference.


1 Answers

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');  
}
like image 189
Andy E Avatar answered Sep 28 '22 06:09

Andy E