All the Web front-end colleagues are very familiar with document.getElementById. Development process often need to use it to get the page ID for XX elements, since the Elder Class JS library prototype popular, like so shorthand it
Copy Code code as follows:
Mode 1
function $ (ID) {return document.getElementById (ID);}
Has anyone ever thought about why you should write it this way instead of writing it down?
Copy Code code as follows:
Mode 2
var $ = document.getElementById;
So it's simpler to write, and it's clear, to assign the document's method getElementById to the variable $, with $ to get the element with the page ID xx. In fact, Mode 2 is feasible in IE6/7/8 (some changes in IE9), and Firefox/safari/chrome/opera is unworkable. Please also test yourself.
Why Firefox/safari/chrome/opera Mode 2 is not possible because these browsers rely on this (document) for internal implementations of getElementById methods, ie do not need this. or mode 2, when invoked in Firefox/safari/chrome/opera, said this was lost, here is a simple example
Copy Code code as follows:
Define a function show
Function Show () {alert (this.name);}
Defines a P object with the name attribute
var p = {name: ' Jack '};
Show.call (P); -> ' Jack '
Show (); -> '
Show.call (NULL); -> ' ' <BR>
You can see that the implementation of show relies on this (simply to say that this is used in the method body), so the environment (execution context) when invoked does not have the desired result if it does not have the Name property.
In other words, IE6/7/8 does not use this when implementing document.getElementById, and Ie9/firefox/safari/chrome/opera needs to use this, where this is the document object. Direct call Mode 2 o'clock the inside of this is the Window object, so it causes mode 2 to not get the element properly based on the ID in Firefox/safari/chrome/opera.
If you change the execution environment for document.getElementById to document instead of window, you can use $ normally. As follows
Copy Code code as follows:
Repair document.getElementById
document.getElementById = (function (FN) {
return function () {
Return fn.apply (document,arguments);
};
}) (document.getElementById);
After the repair is assigned to $,$ can be used normally
var $ = document.getElementById;
Again, the Bind method added to the function in ECMASCRIPT5 can achieve the same effect
Copy Code code as follows:
Mode 3
var $ = document.getElementById.bind (document);
But current mode 3 only has ie9/firefox/chrome/support.
Analysis of the getElementById situation, the following methods in the different browsers in the reason is very good understand
Copy Code code as follows:
var prinf = document.write;
Prinf ('
var prinfln = Document.writeln;
PRINFLN ('
var reload = location.reload;
Reload (); IE6/7/8 can run, other browser error
var go = history.go;
Go (-2); IE6/7/8 can run, other browser error