amd

js 模块的模块化

https://www.ruanyifeng.com/blog/2012/10/asynchronous_module_definition.html

  • 有了模块化,可以使用别人的代码,想要什么功能,加载什么模块;
  • commonjs,amd
  • commonjs:同步加载,require加载完成模块,才能使用模块中的方法,会有等待加载模块的过程,浏览器需要等待,会有假死的存在,不适合浏览器
var math = require('math');
math.add(2, 3);
  • amd:异步加载:所以依赖这个模块的语句,都定义在一个回调函数中,等到模块加载完成之后,回调函数才会执行;
  require(['math'], function (math) {
    math.add(2, 3);
  });
  • require.js和curl.js 采用amd规范
  • 定义amd模块
// 定义
// math.js

  define(function (){

    var add = function (x,y){

      return x+y;

    };

    return {

      add: add
    };

  });
// 使用
// main.js

  require(['math'], function (math){

    alert(math.add(1,1));

  });
// 还依赖其他模块
define(['myLib'], function(myLib){

    function foo(){

      myLib.doSomething();

    }

    return {

      foo : foo

    };

  });


posted @ 2021-12-21 19:22  Running00  阅读(48)  评论(0)    收藏  举报