It does not work as you suggest because the calling object would not be that
referred to by `document' anymore, but the Global Object. As a result, at
least MSHTML would throw an exception. I had to observe that when writing
JSX:dhtml.js years ago and I presume it still holds true. So a wrapper is
required if you want an alias for this, but it should have a better, self-
descriptive identifier (like `dom.getEBI' etc. in JSX:dhtml.js). Since then
this method included also feature testing for the MSHTML 4 and NS 4 DOMs,
but it would appear that these can either be safely discarded in the near
future or moved to compatibility libraries.
I see your case, but I have a few disagreements.
Calling a host method with a different base object won't work in most
browsers. A function call gets its `this` value from that base object.
And for browsers that implement `getElementById` as a function and that
function needs to resolve a thisArg to the document to be searched, then
yes, the global object will be used and an error, either NativeError or
possibly TypeError would probably result.
However it *will* work in most IE versions. This is old news, appearing
in an old post of erik's weblog: "appendChild is not a function" and
restated as recently as two weeks ago wherein it was mentioned that MSIE
host methods tend to retain a reference to the base object.
var meth = document.getElementById;
meth("banner"); // Works in IE.
(Mentioned in "Need help with setTimeout"
<
MSIE host methods are not really functions although they do appear to
implement [[Call]]. This can be tested indirectly using
Function.prototype.call.call, as in:
var meth = document.getElementById;
Function.prototype.call.call(meth, document, "banner")
Exploring host methods further, I see IE9b has host methods appear to be
more like functions in that they have callable properties "call" and
"apply" that are not functions.
javascript: alert(typeof document.getElementById.call)
Though not all:
javascript: alert(typeof alert.call)
And still errors:
javascript: alert(typeof alert.blah = 1);
As far as creating a shortcut for document.getElementById, I can't see
it being justified.
Typing document.getElementById is not too long. Adding an extra function
to do that means your app has one more function in memory and for what
purpose? It's essentially a useless function that saves typing but comes
at a cost of keeping one more function in memory (with a scope chain,
etc) and the overhead of calling that additional function, which isn't
so significant, nowadays, but still redundant.
The only case where I can see using a wrapper is if you need to address
bugs in versions of IE where an element whose NAME attribute matches the
value of the parameter passed to document.getElementById. However, as
was pointed out years ago (I believe Gregor Koefler, said it): How about
just don't do that?
If typing is a problem, then an IDE autocomplete can be helpful.
Intelli-J and Eclipse are both nice.
Garrett