Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js之惰性函数 #51

Open
2018212632 opened this issue Nov 20, 2020 · 0 comments
Open

js之惰性函数 #51

2018212632 opened this issue Nov 20, 2020 · 0 comments
Labels

Comments

@2018212632
Copy link
Owner

js之惰性函数

什么是惰性函数以及作用

惰性载入表示函数执行的分支仅会发生一次。

实现惰性函数的方法有两种,一种是在执行分支的时候覆盖函数;另一种使用函数表达式,在声明函数的时候就给每个分支指定适当的函数。

// 方式一
function f() {
    if(typeof XMLHttpRequest != 'undefined') {
        f = function() {
            // do something
        }
    } else if(typeof ActiveXObject != 'undefined') {
        f = function() {
            // do somethins
        }
    } else {
        f = function() {
            throw new Error('some error')
        }
    }
    return f()
}

// 方式二
var f = (function() {
    if(typeof XMLHttpRequest != 'undefined') {
        return function() {
            // do something
        }
    } else if(typeof ActiveXObject != 'undefined') {
        return function() {
            // do somethins
        }
    } else {
        return function() {
            throw new Error('some error')
        }
    }
})()

惰性函数让函数检测浏览器对XMLHttpRequest的支持只需要执行一次。惰性函数的优点在于只在执行分支代码时牺牲一点性能,但是能过避免执行不必要的代码。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant