美文网首页
AngularJS中立即函数理解

AngularJS中立即函数理解

作者: nzjcnjzx | 来源:发表于2018-12-11 11:16 被阅读0次
    ;(function(window, angular, document){
    
    函数体;
    
    })(window, window.angular, document);
    
    
    
    • 一个普通的函数像这样
     var fn = function(name){
      console.log(name)
    }
    
    fn('张三')
    我们能够在作用域下的任何一处调用它。
    
    我们如何让上面的函数在运行时能立即调用呢?可以像下面这样:
     var fn =( function(name){
      console.log(name)
    })('xiaoming')
    
    立即函数的定义像下面这样:
    
    (function () {
      
    })();
    
    
    虽然几种怪异的写法能欺骗javascript "making it work",这些迫使JavaScript分析器对待下面的代码中的“!”字符作为一个表达式:
    !function () {
      
    }();
    还有一些其他的变种
    +function () {
      
    }();
    -function () {
      
    }();
    ~function () {
      
    }();
    
    
    

    使用立即函数的形式,在我们压缩代码时会更容易的:

    (function (window, document, undefined) {
      console.log(window); // Object window
    })(window, document);
    改变如下:
    (function (a, b, c) {
      console.log(a); // Object window
    })(window, document);
    当然像使用jQuery时常用$,同时我们可以使用其他的代替:
    (function ($, window, document, undefined) {
      // use $ to refer to jQuery
      // $(document).addClass('test');
    })(jQuery, window, document);
     
    (function (a, b, c, d) {
      // becomes
      // a(c).addClass('test');
    })(jQuery, window, document);
    
    

    当在非浏览器环境中,如nodejs,为了适应多种环境,我们定义立即函数像如下这样:

    (function (root) {
     
    })(this);
    下面是一个通用的解决方案,在不同的环境中:
    
    (function (root, factory) {
      if (typeof define === 'function' && define.amd) {
        define(factory); //requireJS
      } else if (typeof exports === 'object') {
        module.exports = factory; //as nodejs
      } else {
        root.MYMODULE = factory(); //in borwser
      }
    })(this, function () {
      // 
    });
    
    

    通过自执行函数解决异步的问题:

    for(var i=0;i<10;i++){
        setTimeout(() => {
            console.log(i)
        }, i * 100);
    }
    // 10 10 10 ...
    for (let i = 0; i < 10; i++) {
      setTimeout(() => {
          console.log(i)
      }, i*100);    
    }
    // 0 1 2 ...
    (function print(i){
        if(i == 10) {
            return
        }
        setTimeout(() =>{
          console.log(i++)
           print(i)
        }, i*100)
    })(0)
    // 0 1 2 ...
    for (var i = 0; i < 10; i++) {
        (function(i) {
            setTimeout(function() { console.log(i); }, 100 * i);
        })(i);
    }
    // 0 1 2 ...
    

    相关文章

      网友评论

          本文标题:AngularJS中立即函数理解

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