美文网首页
立即执行函数(IIFE)

立即执行函数(IIFE)

作者: rocneal | 来源:发表于2016-10-12 01:02 被阅读0次

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

/**
 *  优点:可以传参
 */
(function (){
    // sth
})();

(function IIFE() {
    // sth
})();
/**
 *  优点:节省代码量
 */
(function () {
    // sth
});

(function IIFE() {
    // sth
});
/**
 *  非主流写法,容易引起别人误解,但是最简洁
 */
!function () {
    // sth
}();

!function IIFE() {
    // sth
}();
/**
 *  后调用写法,很多人认为这种写法更容易理解业务结构
 */
(function (def) {
    def(window);
})(function (global) {
    // sth
});

(function IIFE(def) {
    def(window);
})(function def(global) {
    // sth
});

相关文章

网友评论

      本文标题:立即执行函数(IIFE)

      本文链接:https://www.haomeiwen.com/subject/nvzbyttx.html