Init-time branching the initial period branch is an optimized mode. If certain conditions do not change after the program is started, then we only need to check it once during the initial period, not every time we need to use these conditions. For example, JavaScript often needs to decide which browser to run on, and this check is usually done in the initial period. As another example, assuming that the program needs to check for support for XMLHttpRequest objects (important objects in AJAX applications) while it is running, we can assume that the program will always be able to use this object while it is running, if the environment supports it.
JavaScript programmers will need to support some features in the runtime environment, such as the following code:
Beforevar utils = { addlistener:function (el, type, fn) { if (typeof window.addeventlistener = = = ' function ') { el.addeventlistener (Type, FN, false); } else if (typeof document.attachevent = = = ' function ') {//IE el.attachevent (' on ' + type, fn); } else {//older BR Owsers el[' on ' + type] = fn; } , removelistener:function (el, type, fn) { //pretty much the same. . }};
There is no logical error in this code, and the problem is that the operation is inefficient. Because every time AddListener checks whether the operating environment supportsWindow.addeventlistener, this is obviously a bit superfluous. Using the method of the initial period branch, the program can be changed to:
after//the Interfacevar utils = { Addlistener:null, removelistener:null};//the implementationif (typeof win Dow.addeventlistener = = = ' function ') { Utils.addlistener = function (el, type, fn) { El.addeventlistener (type, FN, false); }; Utils.removelistener = function (el, type, fn) { el.removeeventlistener (type, FN, false), }, and else if (typeof Docu Ment.attachevent = = = ' function ') {//IE Utils.addlistener = function (el, type, fn) { el.attachevent (' on ' + type, fn); }; Utils.removelistener = function (el, type, fn) { el.detachevent (' on ' + type, fn); };} else {//older browsers
utils.addlistener = function (el, type, fn) { el[' on ' + type] = fn; }; Utils.removelistener = function (el, type, fn) { el[' on ' + type] = null; };}
Finally, it is recommended that you do not make too many "guesses" about the running environment. For example, the operating environment does not support Window.addeventlistener, does not mean that it must be ie, does not mean that it does not support XMLHttpRequest. Therefore, it is best to consider the characteristics of these operating environments as independent and unrelated conditions to check.
JavaScript Base initial period branch (018)