Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS模块规范 #1

Open
trimmeryang opened this issue Jul 5, 2017 · 0 comments
Open

JS模块规范 #1

trimmeryang opened this issue Jul 5, 2017 · 0 comments

Comments

@trimmeryang
Copy link
Owner

trimmeryang commented Jul 5, 2017

AMD (异步模块规范)

1 下面是只依赖jquery的模块foo的代码:

//    文件名: foo.js
define(['jquery'], function ($) {
    //    方法
    function myFunc(){};
 
    //    暴露公共方法
    return myFunc;
});

2 依赖了多个组件并且暴露多个方法

// 文件名: foo.js
define(['jquery', 'underscore'], function ($, _) {
// 方法
function a(){}; // 私有方法,因为没有被返回(见下面)
function b(){}; // 公共方法,因为被返回了
function c(){}; // 公共方法,因为被返回了
     //    暴露公共方法
    return {
        b: b,
        c: c
    }
});

CommonJS

//    文件名: foo.js
//    依赖
var $ = require('jquery');
//    方法
function myFunc(){};
 
//    暴露公共方法(一个)
module.exports = myFunc;
//    文件名: foo.js
var $ = require('jquery');
var _ = require('underscore');
 
//    methods
function a(){};    //    私有方法,因为它没在module.exports中 (见下面)
function b(){};    //    公共方法,因为它在module.exports中定义了
function c(){};    //    公共方法,因为它在module.exports中定义了
 
//    暴露公共方法
module.exports = {
    b: b,
    c: c
};

#UMD: 通用模块规范

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS之类的
        module.exports = factory(require('jquery'));
    } else {
        // 浏览器全局变量(root 即 window)
        root.returnExports = factory(root.jQuery);
    }
}(this, function ($) {
    //    方法
    function myFunc(){};
 
    //    暴露公共方法
    return myFunc;
}));
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery', 'underscore'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS之类的
        module.exports = factory(require('jquery'), require('underscore'));
    } else {
        // 浏览器全局变量(root 即 window)
        root.returnExports = factory(root.jQuery, root._);
    }
}(this, function ($, _) {
    //    方法
    function a(){};    //    私有方法,因为它没被返回 (见下面)
    function b(){};    //    公共方法,因为被返回了
    function c(){};    //    公共方法,因为被返回了
 
    //    暴露公共方法
    return {
        b: b,
        c: c
    }
}));

来自阮一峰的描述
2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant