underscore.js對javascript來說是一個蠻好用的工具, 在前端應用程式的開發中也很常被利用到,但同樣以javascript為基礎開發的node.js, 能否直接使用underscore.js呢?
嘗試以下面的程式碼用node.js跑:
require('./underscore.js');
var a = [1, 23, 6, 11, 25, 12, 33, 11, 4];
_.forEach(a, function(v) {
console.log(v);
});
執行結果會得到"ReferenceError: _ is not defined"
打開underscore.js的原始碼一看, 發現了這一段, 其實它是有針對node.js做手腳的:
// 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['_'] = _;
}
也就是, 在browser時, "_"是一個global object, 但在node.js則不是, 原本的範例如果改成這樣就可以了:
var _us = require('./underscore.js');
var a = [1, 23, 6, 11, 25, 12, 33, 11, 4];
_us.forEach(a, function(v) {
console.log(v);
});
這樣一來, 前後端也可以共用同一份underscore.js了
補充: 類似的工具還有async這個, 也是前後端都可以應用
----- 10/11 補充 -----
寫這篇的時候真的是沒睡飽, 沒注意看underscore放在github上的內容, 它已經弄好node module了, 所以只要:
npm install underscore就可以裝好了, code裡面也只需要用"var _us = require('underscore')"
沒有留言:
張貼留言