我们必须承认本地JavaScript的不完善,正是如此,才有了那么多完善它的框架,例如jQuery,mootools,prototype等等。今天我们不讨论框架,而是来探讨一下可以拓展JavaScript功能的额外插件,它们通常是通过拓展类、字符串、日期和对象等实现的。
举个例子,JavaScript现有的Date函数的局限性就很明显。而SugarJS增加了40种以上的日期操作函数,以下是其中的一部分:
Date.create(d,locale):支持多种格式的日期构造函数
compare(obj):日期的数值比较
Format(format,locale):将日期格式化
isLeapYear():如果是闰年则返回真
其他
我们相信本文中提到的三种JS库将会给您带来帮助。当然,如果你还知道其他的,欢迎和我们分享。
1.SUGAR
Sugar给我们带来了一些有用的方法,让你能够用更少的代码完成更多的事。
例:
getLatestTweets(function(t) {
var users = t.map('user').unique();
var total = users.sum('statuses_count').format();
var top = users.max('followers_count').first();
var count = top.followers_count.format();
var since = Date.create(top.created_at);
return users.length + ' users with a total of ' + total + ' tweets.n' +
top.screen_name + ' is the top with ' + count + ' followersn' +
'and started tweeting ' + since.relative() + '.';
});
/*
Result:
>20 users with a total of 211,776 tweets.
TagalogQuotes is the top with 68,554 followers
and started tweeting 7 months ago.
*/
2.UNDERSCORE.JS
和sugarjs类似,underscore.js提供了许多不拓展内置对象的函数支持。Underscore支持60多个函数,既包括常用函数对象:map,select,invoke——以及更多专业工具:function binding,javascript templating,deep equality testing等等。它委托给内置函数,所以现代浏览器通过each,map,reduce,filter,every,some和indexOf实现本地功能运用。
例:
_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]
_.first([5, 4, 3, 2, 1]);
=> 5
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name : 'moe'}, 'hi');
func();
=> 'hi: moe'
var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'
3.PHP.JS
PHP.JS实现了PHP现有函数的JavaScript版本。作为一个PHP开发人员,我惊讶于它的模仿程度之高。
例:
function array_merge () {
var args = Array.prototype.slice.call(arguments),
argl = args.length,
arg,
retObj = {},
k = '',
argil = 0,
j = 0,
i = 0,
ct = 0,
toStr = Object.prototype.toString,
retArr = true;
for (i = 0; i < argl; i++) {
if (toStr.call(args[i]) !== '[object Array]') {
retArr = false;
break;
}
}
if (retArr) {
retArr = [];
for (i = 0; i < argl; i++) {
retArr = retArr.concat(args[i]);
}
return retArr;
}
for (i = 0, ct = 0; i < argl; i++) {
arg = args[i];
if (toStr.call(arg) === '[object Array]') {
for (j = 0, argil = arg.length; j < argil; j++) {
retObj[ct++] = arg[j];
}
}
else {
for (k in arg) {
if (arg.hasOwnProperty(k)) {
if (parseInt(k, 10) + '' === k) {
retObj[ct++] = arg[k];
}
else {
retObj[k] = arg[k];
}
}
}
}
}
return retObj;
}
如果你知道其他好的JS库的话,请一定记得和大家分享哦。
达维营-前端网