zoukankan      html  css  js  c++  java
  • Javascript 函数和模块定义

    匿名函数

    // calculator.js
    (function(root) {
      var calculator = {
        sum: function(a, b) { return a + b; }
      };
      root.Calculator = calculator;
    })(this);

    // app.js
    console.log(Calculator.sum(1, 2)); // => 3 

    一个例子:

    (function (root, ns, factory) {
        // some code
    } (window, 'detectZoom', function() {
        // some more code
    }));

    There is an anonymous function taking three parameters (root, ns, factory) which is immediately invoked.

    • root takes the value of`window.
    • ns takes the value of 'detectZoom'
    • factory takes the value of callback function (also anonymous)

    The explanation:

    (function (root, ns, factory) {
       // the body of the anonymous function
    } (window, 'detectZoom', function() {
       // the body of the 'factory' callback
    }));

    To break it apart, how to get to this code in four steps:

     1.
     // Anonymous function.
     (function (root, ns, factory) {/* body */});
    
     2.
     // Anonynmous function, immediately invoked
     (function (root, ns, factory) {/* body */})();  // parentheses mean it's invoked
    
     3.
     // Callback as a separate argument
     var cbk = function () {};
     (function (root, ns, factory) {/* body */})(window, 'detectZoom', cbk);
    
     4.
     // Callback as an anonymous function
     (function (root, ns, factory) {/* body */})(window, 'detectZoom', function () {});

    You could rewrite your code to be more verbose:

    var outer = function (root, ns, factory) {
      // the body
    };
    
    var callback = function () {
      // the body
    };
    
    outer(window, 'detectZoom', callback);

    三种模块定义方式
    1) es6

    // calculator.js
    export function sum(a, b) {
      return a + b;
    };

    // app.js
    import calculator from "calculator";

    console.log(calculator.sum(1, 2));

    2. common

    // calculator.js
    module.exports.sum = function (a, b) {
      return a + b;
    };

    // app.js
    var calculator = require("calculator");

    console.log(calculator.sum(1, 2));

    3. Amd
    // calculator.js
    define({
      sum: function(a, b) {
        return a + b;
      }
    });

    // app.js
    define(["./calculator"], function(calculator) {
      console.log(calculator.sum(1, 2));
    });
  • 相关阅读:
    剑指offer39-平衡二叉树
    剑指offer37-数字在排序数组中出现的次数
    剑指offer36-两个链表的第一个公共结点
    剑指offer31-整数中1出现的次数
    剑指offer30-连续子数组的最大和
    剑指offer28-数组中出现次数超过一半的数字
    剑指offer26-二叉搜索树与双向链表
    剑指offer21-栈的压入、弹出序列
    剑指offer16-合并两个排序的链表
    C#-杂碎
  • 原文地址:https://www.cnblogs.com/qiangxia/p/5379195.html
Copyright © 2011-2022 走看看