JS中的惰性函数

最近在网上看一个关于惰性函数的例子,觉得非常不错,就记下来。

/**
 * Created by DreamCatcher on 2018/4/26.
 */
function createXHR () {
    var xhr = null;
    try {
        //Firefox, Opera8.0+, Safari, IE7+
        xhr = new XMLHttpRequest();
    } catch (e) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                xhr = null;
            }
        }
    }
    return xhr;
}

/*
   惰性函数
 */
function createXHR () {
    var xhr = null;
    if (XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        createXHR = function () {
            return new XMLHttpRequest();
        }
    } else {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
            createXHR = function () {
                return new ActiveXObject("Msxml2.XMLHTTP");
            }
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
                createXHR = function () {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            } catch (e) {
                xhr = null;
                createXHR = function () {
                    return null;
                }
            }
        }
    }
    return xhr;
}

以下是第二种实现方式:

var addEvent = (function () {
    if (document.addEventListener) {
        return function (type, element, fun) {
            element.addEventListener(type, fun, false);
        }
    }
    else if (document.attachEvent) {
        return function (type, element, fun) {
            element.attachEvent('on' + type, fun);
        }
    }
    else {
        return function (type, element, fun) {
            element['on' + type] = fun;
        }
    }
})();

猜你喜欢

转载自blog.csdn.net/hsl0530hsl/article/details/80099108