zoukankan      html  css  js  c++  java
  • 自执行匿名函数语法和普通函数语法对比

    var eatFunction = function (what_to_eat) {
      var sentence = 'I am going to eat a ' + what_to_eat;
      console.log( sentence );
    };
    eatFunction( 'sandwich' );
    
    // is the same as
    
    (function (what_to_eat) {
      var sentence = 'I am going to eat a ' + what_to_eat;
      console.log(sentence);
    })('sandwich');
    
    // is the same as
    
    (function (what_to_eat) {
      var sentence = 'I am going to eat a ' + what_to_eat;
      console.log(sentence);
    }('sandwich')); 
    
    // Three of them output 'I am going to eat a sandwich'
    

      唯一的区别是,变量 eatFunction 被移除了,使用一对括号把函数定义包了起来。

    示例:

    自执行匿名函数

    var counter = (function() {
      var count = 0;
      var get = function() {
        count++;
        return count;
      }
      return get;
    })();
    
    console.log(counter()); //输出 1
    console.log(counter()); //输出 3
    console.log(counter()); //输出 3
    

     普通函数

    var generateClosure = function() {
      var count = 0;
      var get = function() {
        count++;
        return count;
      }
      return get;
    };
    
    var counter = generateClosure();
    console.log(counter()); //输出 1
    console.log(counter()); //输出 3
    console.log(counter()); //输出 3
    
  • 相关阅读:
    E寻宝(贪心)
    千万别点进来,点进来你就哭了(最短路,dijkstra)
    H小明买年糕(前缀和+二分)
    Charles破解
    Jmeter安装插件
    appium环境搭建
    SourceTree安装和教程
    Appium-desktopAppium-desktop 安装与入门使用
    appium终端安装
    Seleinum_CSS定位方式
  • 原文地址:https://www.cnblogs.com/nodejsxxh/p/4421137.html
Copyright © 2011-2022 走看看