一种封装 JavaScript 的方法

推荐这种封装方式,可支持 seajs , nodejs, jQuery

(function(factory) {
    if (typeof define === 'function') {
        // seajs support
        define(factory);
    } else if (typeof require === 'function') {
        // nodejs support
        factory(require, exports, module);
    } else {
        factory();
    }
})(function(require, exports, module) {
    var global = this;  // window

    function yourLibrary() {}

    // CommonJS compatable
    if (typeof module !== 'undefined') {
        module.exports = yourLibrary;
    } else {
        global.yourLibrary = yourLibrary;
    }
    // jQuery plugin support
    if (typeof jQuery !== 'undefined') {
        jQuery.fn.yourLibrary = yourLibrary;
    }
})

可参考最近写的一个小东西 selection.js

7 comments