如何封装Node.js和前端通用的模块

前端模块一般是咱们开发人员为了不和他人冲突才把模块代码放置在一个闭包中。css

如何封装Node.js和前端通用的模块,咱们能够参考Underscore.js 实现,他就是一个Node.js和前端通用的功能函数模块,查看代码:前端

如何封装Node.js和前端通用的模块,咱们能够参考Underscore.js 实现,他就是一个Node.js和前端通用的功能函数模块,查看代码:浏览器

// Create a safe reference to the Underscore object for use below.闭包

  var _ = function(obj) {app

    if (obj instanceof _) return obj;ide

    if (!(this instanceof _)) return new _(obj);函数

    this._wrapped = obj;ui

  };this

 

  // Export the Underscore object for **Node.js**, withspa

  // backwards-compatibility for the old `require()` API. If we're in

  // the browser, add `_` as a global object via a string identifier,

  // for Closure Compiler "advanced" mode.

  if (typeof exports !== 'undefined') {

    if (typeof module !== 'undefined' && module.exports) {

      exports = module.exports = _;

    }

    exports._ = _;

  } else {

    root._ = _;

  }

经过判断exports是否存在来决定将局部变量 _ 赋值给exports,向后兼容旧的require() API,若是在浏览器中,经过一个字符串标识符“_”做为一个全局对象;

相关文章
相关标签/搜索