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/
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.
Scope determines the accessibility of variables, objects, and functions from different parts of the code.
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With