[JavaScript]偶自己的JavaScript扩展库(一点一点完善中...)
所有的对内置对象扩展的方法都是以x(stands for 'extend')开头, 非扩展内置对象的方法按英文原意命名, 然后命名空间为wf(stands for wind fantasy)
Object.prototype.xattach = function (obj, nooverwrite) { for (var prop in obj) { // if the property exists and disallow the property to be overwritten, just skip if (typeof this[prop] != 'undefined' && nooverwrite) { continue; } this[prop] = obj[prop]; } return this; } String.xattach({ xrepeat: function (repeat, times) { return new Array(times+1).join(repeat); } }); String.prototype.xattach( { xrepeat: function (times) { return String.xrepeat(this, times); } }); Array.xattach({ 'xrange': function (start, stop, step) { // python-like range var value, range = []; if (arguments.length == 1) { stop = start; start = 0; } if (isNaN(stop) || isNaN(start)) { return null; } if (isNaN(step) || step == 0) step = start < stop ? 1 : -1; if (step > 0) { for (value = start; value < stop; value += step) range.push(value); } else { for (value = start; value > stop; value += step) range.push(value); } return range; } }); Array.prototype.xattach({ // toString: function () { // better toString // return ' [' + this.join(',') + '] '; // }, xcopy: function () { // shallow copy return this.slice(); }, // [1,2,3,4,5].xgroup(2) => [ [1,2], [2,3], [3,4], [4,5] ] xgroup: function (count) { // group all subsequences of which the length is count from this var i, targetlen = this.length - count + 1, target = []; for (i = 0; i < targetlen; ++i) target[i] = this.slice(i, i+count); return target; }, // ['a', 'b', 'c']; xmap(null, parseInt, true, 16) => [10, 11, 12] // if you don't want to change array itsself and wanna get the return value, you // can do like this: arr.xcopy().xmap(null, parseInt, true, 16) // just change its (shallow) copy xmap: function (thisobj, func, changeself, extraargs) { // map this with thisobj.fuc var i = 0, len = this.length; if (! (extraargs instanceof Array)) { extraargs = Array.prototype.slice.call(arguments, 3); } if (changeself) { for (i=0; i < len; ++i) { this[i] = func.apply(thisobj, [ this[i] ].concat(extraargs)); } } else { for (i=0; i < len; ++i) { func.apply(thisobj, [ this[i] ].concat(extraargs)); } } return this; } });
posted on 2011-11-23 16:23 Wind__Fantasy 阅读(370) 评论(0) 编辑 收藏 举报