扩展原型方法
//Add a method conditionally.
Function.prototype.method=function(name,func){
if(!this.prototype[name]){
this.prototype[name]=func;
}
};
上面的代码功能类似于
Function.prototype.someMethod=Function.prototype.someMethod||function(){}
可以避免粗鲁覆盖原型中已有的某些方法,而且你不需要每次都写'prototype'。
数组的一些基本方法的实现方式
1 Array.splice(start,deleteCount,item...)
/*
* [--start(------deleteCount-----)(--shiftCount--)]
* [--start(-insertCount-)(-delta-)(--shiftCount--)]
* [--start(---------insertCount-----------)(--shiftCount--)]
* (-delta-)
*/
Array.method("mySplice", function (start, deleteCount) {
start = start || 0;
if (start < 0) {
start += len;
}
start = max(min(start, len), 0);
deleteCount = max(min(typeof deleteCount === "number" ?
deleteCount : len, len - start), 0);
var max = Math.max,
min = Math.min,
k = 0,
len = this.length,
insertCount = max(arguments.length - 2, 0),
shiftCount = len - start - deleteCount,
delta = insertCount - deleteCount,
newLen = len + delta,
result = [];
for (var i = 0; i < deleteCount; i++) {
if(this[start + i] !== 'undefined'){ //sparse array
result[i] = this[start + i];
}
}
if (delta < 0) {
k = start + insertCount;
while (shiftCount) {
this[k] = this[k - delta];
shiftCount--;
k++;
}
}
if (delta > 0) {
k = 1;
while (shiftCount) {
this[newLen - k] = this[len - k];
shiftCount--;
k++;
}
this.length = newLen; //update length
}
for (var j = 0; j < insertCount; j++) {
this[start + j] = arguments[2 + j];
}
return result;
});
备注:JavaScript中的数组为稀疏数组,增大length在firebug中会以'undifined'扩展数组,chrome控制台中数组不变,减小length会截断数组,length大小为数组最后一个元素的索引值加1(并不总是等于元素个数);
Array.splice()返回一个包含删除元素的数组,删除添加都在原数组上进行操作(区别于Array.slice()),所以可以用于删除数组元素;
delete操作同样可以删除数组元素,但是会使数组稀疏化(后面的元素索引不变,留下一个“洞”在原数组上);
2 Array.pop()
Array.method("myPop",function(){
return this.splice(this.length - 1, 1)[0]; //splice() method returns an array
});
3 Array.push()
Array.method("myPush",function(){
this.splice.apply(this, [this.length, 0].concat(Array.prototype.slice.apply(arguments)));
return this.length; //push() method returns the length of the array
});
4 Array.shift()
Array.method("myShift",function(){
return this.splice(0,1)[0];
});
5 Array.unshift()
Array.method("myUnshift",function(){
this.splice.apply(this, [0, 0].concat(Array.prototype.slice.apply(arguments)));
return this.length;
});
备注:pop/push/shift/unshift/方法均改变了原数组,所以用splice()方法实现;
splice()方法返回的是数组,要加上索引‘[0]’才能正确的实现pop/push等方法;
Array.prototype.slice.apply()可以将arguments类数组转化为数组,再传入concat方法;
apply的两个作用,1 对象冒充;2 传入数组参数;
REFERENCE: JavaScript花园、JavaScript精粹、JavaScript权威指南、网络资料