AMD随译

作者: 野薇薇 | 来源:发表于2016-11-30 10:41 被阅读0次

    amd原文

            由于commenJs 本身是同步的所以有些人认为它并不适合浏览器,对此AMD即(Asynchronous Module Definition)给出了最好的回应。

           AMD制定了模块化js的标准,因此模块可以异步载入所依赖的文件,解决与同步加载的问题。

    说明:

    模块的定义需要使用 define 函数

    define:

    define(id?: String, dependencies?: String[], factory: Function|Object);

    id:

    模块的名称,可选的

    dependencies

    此参数为被定义的模块所含有的依赖模块,它是一个含模块标示符的数组。可选,如果省略,默认为【“require”,“exports”,“module”】

    factory

    最后一个参数,用来定义模块,可以是一个函数(可调用一次),也可以是一个对象。如果factory是一个函数,函数的返回值将作为模块的输出值。

    Example

    定义一个名为myModule的模块,需要jQuery

    define('myModule', ['jquery'],function($){

    // $ is the export of the jquery module. $('body').text('hello world');});

    // and use it require(['myModule'],function(myModule){});

    注意:在webpack中定义的模块局部有效,Require中定义的模块全局有效

    同步模块

    定义一个未指明id的模块

    define(['jquery'],function($){$('body').text('hello world');});

    多个依赖

    定义依赖多个文件的模块,注意:每一个依赖的文件输出都系要传递给factory

    define(['jquery','./math.js'],function($, math){// $ and math are the exports of the jquery module.$('body').text('hello world');});

    输出值

    定义一个输出自身的模块

    define(['jquery'],function($){varHelloWorldize =function(selector){$(selector).text('hello world');    };returnHelloWorldize;});

    使用 require 载入依赖文件

    define(function(require){var$ = require('jquery');    $('body').text('hello world');});

    相关文章

      网友评论

          本文标题:AMD随译

          本文链接:https://www.haomeiwen.com/subject/vvozpttx.html