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

本文介绍了一种封装Node.js和前端通用模块的方法,并以Underscore.js为例进行详细解析。通过这种方式,开发人员可以避免代码冲突并提高代码复用率。

前端模块通常是我们开发人员为了避免和他人冲突才把模块代码放置在一个闭包中。

如何封装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) {

    if (obj instanceof _) return obj;

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

    this._wrapped = obj;

  };

 

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

  // 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,如果在浏览器中,通过一个字符串标识符“_”作为一个全局对象;




转载于:https://my.oschina.net/u/1403171/blog/200574

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值