zoukankan      html  css  js  c++  java
  • ~function(){}() 和(function(){}){}

    使用~function(){}()也是声明并调用函数的方法之一:

    这是一段使用~function(){}()来声明函数并调用函数的例子:

      ~function() {
        alert(typeof next) // undefined
        ~function next() {
          alert(typeof next) // function
        }()
      }();

    把外层换成(function(){})()如下:

      (function() {
        alert(typeof next); // undefined
        (function next() {
          alert(typeof next); // function
        })()
      })();

    通过火狐开发工具,可以发现,这两段代码在执行的过程中没有任何区别.

    如果是声明但不调用函数:

    (function() {
      alert(typeof next); // undefined
      function next() {
        alert(typeof next); 
      }
      next();  // function
    })();

    使用function next(){}这种方式声明的函数,会预解析.

    使用~来声明函数:

    (function() {
      alert(typeof next); // undefined
      ~function next() {
        alert(typeof next); 
      };
      next();  //会报错
    })();

    使用这种方式不能声明函数.

      

    另外,使用~方式声明并调用的函数,返回值会通过~计算,得到不想要的返回值,如下:

    alert(!function (){alert('hello');return false;}());  //true
    alert(~function (){alert('hello');return false;}());  //-1

    总结:

    1.使用~function(){}()和使用(function(){})()没有区别.

    2.使用~function name(){}(),函数内部可以访问到自己,但是离开了函数体,外层访问不到name函数

    3.不能使用~来创建函数,只能创建的同时调用

    4.~是一个位运算符,所以会将函数的返回值进行位运算,得到的返回值不是想要的返回值.

  • 相关阅读:
    shell-3
    shell-2
    shell-1
    zabbix监控top
    django指导网址
    文件下载漏洞
    Build a Raspberry Pi powered live train station sign for your desk
    Use a Raspberry Pi to communicate with Amazon AWS IoT
    Describing and Listing Your Stacks
    固有功能参考 Intrinsic Function Reference
  • 原文地址:https://www.cnblogs.com/liulangmao/p/3476259.html
Copyright © 2011-2022 走看看