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
    
  • 相关阅读:
    2014年广州区域赛k题解
    2014年广州区域赛e题解
    2014年广州区域赛i题解
    最大化平均值问题
    codeforces 976e 题解
    maven
    机器学习入门
    拟合
    插值
    熵权法
  • 原文地址:https://www.cnblogs.com/nodejsxxh/p/4421137.html
Copyright © 2011-2022 走看看