zoukankan      html  css  js  c++  java
  • 匿名函数自调用(IIFE)

    什么是匿名函数

    Javascript中定义函数的方式有多种,函数直接量就是其中一种。如var fun = function(){},这里function如果不赋值给fun那么它就是一个匿名函数。好,看看匿名函数的如何被调用。

    调用方式

    1:调用函数,得到返回值。强制运算符使函数调用执行

    (function(x,y){
        alert(x+y);
        return x+y;
    }(3,4));
    

    2:调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用再去调用执行

    (function(x,y){
        alert(x+y);
        return x+y;
    })(3,4); 
    

    这种方式也是很多库爱用的调用方式,如jQueryMootools

    3:使用void

    void function(x) {
          x = x-1;
          alert(x);
    }(9);       
    

    4:使用-/+运算符

    -function(x,y){
        alert(x+y);
        return x+y;
    }(3,4);
    
    +function(x,y){
        alert(x+y);
        return x+y;
    }(3,4);
    
    --function(x,y){
        alert(x+y);
        return x+y;
    }(3,4);
    
    ++function(x,y){
        alert(x+y);
        return x+y;
    }(3,4);
    

    5:使取反运算符(~)

    ~function(x, y) {
        alert(x+y);
       return x+y;
    }(3, 4);
    

    6:匿名函数执行放在中括号内

    [function(){
       console.log(this) // 浏览器得控制台输出window
    }(this)]
    

    7:匿名函数前加typeof

    typeof function(){
       console.log(this) // 浏览器得控制台输出window
    }(this)
    

    8:匿名函数前加delete

    delete function(){
       console.log(this) // 浏览器得控制台输出window
    }(this)   
    

    9:匿名函数前加void

    void function(){
       console.log(this) // 浏览器得控制台输出window
    }(this)
    

    10:使用new方式,传参数

    new function(win){
       console.log(win) // window
    }(this)
    

    11:使用new,不传参数

    new function(){
        console.log(this) // 这里的this就不是window了
    }  
    

    12:逗号运算符

    1, function(){
        console.log(this) // window
    }();
    

    13:按位异或运算符

    1^function(){
        console.log(this) // window
    }();
    

    14:比较运算符

    1>function(){
        console.log(this) // window
    }();
    

    帮助文档

    http://1.hehongwei44.sinaapp.com/?p=399

  • 相关阅读:
    webstrom的热更新没效果
    按钮文字有间距并居中
    兄弟选择器(+ 和 ~)
    ES6精简要点
    自动类型转换之运算符重载
    自动类型转换之构造函数
    运算符重载(三)
    运算符重载(二)
    运算符重载(一)
    友元
  • 原文地址:https://www.cnblogs.com/happyty/p/4977186.html
Copyright © 2011-2022 走看看