- Mastering JavaScript Functional Programming
- Federico Kereki
- 323字
- 2021-07-02 22:41:15
Detecting Ajax
Let's go back a bit to the times when Ajax started to appear. Given those different browsers implemented Ajax calls in distinct fashions, you would always have to code around those differences:
function getAjax() {
let ajax = null;
if (window.XMLHttpRequest) {
// modern browser? use XMLHttpRequest
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// otherwise, use ActiveX for IE5 and IE6
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("No Ajax support!");
}
return ajax;
}
This worked but implied that you would re-do the Ajax check for each and every call -- even though the results of the test wouldn't ever change. There's a more efficient way to do so, and it has to do with using functions as first-class objects. We could define two different functions, test for the condition only once, and then assign the correct function to be used later:
(function initializeGetAjax() {
let myAjax = null;
if (window.XMLHttpRequest) {
// modern browsers? use XMLHttpRequest
myAjax = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
// it's ActiveX for IE5 and IE6
myAjax = function() {
new ActiveXObject("Microsoft.XMLHTTP");
};
} else {
myAjax = function() {
throw new Error("No Ajax support!");
};
}
window.getAjax = myAjax;
})();
This piece of code shows two important concepts. First, we can dynamically assign a function: when this code runs, window.getAjax (that is, the global getAjax variable) will get one of three possible values, according to the current browser. When you later call getAjax() in your code, the right function will execute, without needing to do any further browser detection tests.
The second interesting idea is that we define the initializeGetAjax function, and immediately run it -- this pattern is called IIFE, standing for Immediately Invoked Function Expression. The function runs, but cleans after itself, for all its variables are local, and won't even exist after the function runs. We'll see more about this later.
- 嵌入式軟件系統(tǒng)測試:基于形式化方法的自動化測試解決方案
- Linux C/C++服務(wù)器開發(fā)實(shí)踐
- LabVIEW入門與實(shí)戰(zhàn)開發(fā)100例
- Learn Swift by Building Applications
- Java程序設(shè)計(jì)與實(shí)踐教程(第2版)
- 小程序開發(fā)原理與實(shí)戰(zhàn)
- TradeStation交易應(yīng)用實(shí)踐:量化方法構(gòu)建贏家策略(原書第2版)
- MATLAB 2020從入門到精通
- RISC-V體系結(jié)構(gòu)編程與實(shí)踐(第2版)
- Clojure Reactive Programming
- Unity Character Animation with Mecanim
- Webpack實(shí)戰(zhàn):入門、進(jìn)階與調(diào)優(yōu)(第2版)
- 遠(yuǎn)方:兩位持續(xù)創(chuàng)業(yè)者的點(diǎn)滴思考
- Mastering PowerCLI
- Java核心編程