自调用执行函数,怎么使用AMD规范写成一个模块?

   var myservice = (function() {
    var me = this;
    me.reportInfo = {};
    this.setReportInfo = function(data){
       me.reportInfo = data;
    };
    this.getReportInfo = function(){
       return me.reportInfo;
      };

    return me;
   })();

怎么将这一个js文件的内容定义为AMD规范的模块化,就像jQuery,我直接在require.config()引入,在其他多个不同的js文件中直接就可以使用myservice这个调用里面的任意一个方法。

阅读 4.9k
3 个回答

题主你都说jQuery了,参考一下jQuery的实现?

摘自jQuery 2.0源码片段

// Register as a named AMD module, since jQuery can be concatenated with other
    // files that may use define, but not via a proper concatenation script that
    // understands anonymous AMD modules. A named AMD is safest and most robust
    // way to register. Lowercase jquery is used because AMD module names are
    // derived from file names, and jQuery is normally delivered in a lowercase
    // file name. Do this after creating the global so that if an AMD module wants
    // to call noConflict to hide this version of jQuery, it will work.
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function () { return jQuery; } );
    }
var myservice = (function() {
    var me = this;
    me.reportInfo = {};
    this.setReportInfo = function(data){
       me.reportInfo = data;
    };
    this.getReportInfo = function(){
       return me.reportInfo;
      };

    return me;
   })();
if ( typeof define === "function" && define.amd ) {
        define( "myService", [], function () { 
            return myservice;
         } );
    }

这样?

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
    }
}));