关于 Common JS(一)

去年开始逛博客的时候,第一次听到了 BackboneJS,后来真正学的却是AngularJS。

在用Angular $resource 的时候,对于异步总是想用同步的方式去开发,傻乎乎的不会用,直到翻api 的时候发现$q.

Angular Documentation 上关于$q 的定义是:

“A promise/deferred implementation inspired by Kris Kowal's Q. The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.”

翻译如下:

$q 是一个受Kris Kowal's Q启发而实现的 promise/deferred.  CommonJS Promise 规范描述了一个promise 接口,用对象表示异步事件的执行结果,同时在任何特定的时候(异步事件执行完毕)返回完成或未完成。

什么是CommonJS?

CommonJS 官方的描述是:

"JavaScript is a powerful object oriented language with some of the fastest dynamic language interpreters around. The official JavaScript specification defines APIs for some objects that are useful for building browser-based applications. However, the spec does not define a standard library that is useful for building a broader range of applications.

The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java. The intention is that an application developer will be able to write an application using the CommonJS APIs and then run that application across different JavaScript interpreters and host environments. With CommonJS-compliant systems, you can use JavaScript to write:

  • Server-side JavaScript applications
  • Command line tools
  • Desktop GUI-based applications
  • Hybrid applications (Titanium, Adobe AIR)"
翻译如下:
Javascript 是一门强力的面向对象同时有最快速的动态语言解析器所支持的语言,官方的Javascript规范规定了基于对象的API去更好的构建基于浏览器的应用。然而,这些规范没能规范出一个标准的库去支持 构建一个更加广泛意义上的的应用程序。
CommonJS API 将会通过定义APIS 的方式去处理大多数common application 的需要,最终提供一个如同Python、Ruby和Java一样丰富的标准化的库。目的在于应用程序开发者能够通过使用CommonJS APIs 的方式完成兼容不同JavaScript 解释引擎和主机环境的应用程序。通过使用符合CommonJS 标准的系统,你可以用JavaScript 写出:
  • 服务器端的应用程序
  • 命令行工具
  • 基于桌面GUI的应用程序
  • 混合应用 (Titanium, Adobe AIR)

所以CommonJS 是一个......
实现标准!
这个标准通过扩展JavaScript 原有API标准去提升JavaScript 开发应用程序的能力。
JavaScript 现有标准来自于ECMAScript5。里面封装的API还属于上个时代的,基于浏览器而使用的。稀少的API以及数据类型甚至缺乏基本模块化(当然可以通过编程实现),身上仍然带有这门语言仓促创立之初的不足甚至是缺陷。


在实现CommonJS标准后,JavaScript 基本API将得到扩充,具有很多之前不具备的能力,比如字节流,再比如buffer。

一个基于CommonJS实现是NodeJS,基于CommonJS的实现,让Nodejs 在模块化,扩展性,可用性方面相比浏览器端的JavaScript 有了很大的提高。这里稍微扯一点Nodejs开发过程中有意思的一件事情。

在Nodejs 早期的几个版本中,开发者Ryan Dahl 采用的是Promise 的方式进行处理回调,但在2010年2月之后 Ryan Dahl 决定采用Callback 的方式处理。这一决定给NodeJS下基于promise 的实现腾出了舞台。最著名的莫过于 KrisKowal 的$q,这一版本client 以及在 nodejs下都有实现版。而AngularJS下的则是他们团队受到 Kris Kowal 的 Q影响而实现的一个promise 精简版。


扯了这么多,接下来将对CommonJS上的wiki 进行翻译。

未完待续。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值