首页 新闻 会员 周边 捐助

大家看一下为什么上面的each函数,没有用this指针,这里还要用each.call,牛人请指点

0
悬赏园豆:20 [已解决问题] 解决于 2010-03-22 21:23
代码
/*Array*/

A
= function(){

var ret = {
isArray:
function( obj ) {
return Object.prototype.toString.call(obj) === "[object Array]";
},
indexOf:
function( array, elt, from ){
if (array.indexOf) {
return isNaN(from) ? array.indexOf(elt) : array.indexOf(elt, from);
}
else {
var len = array.length;
from
= isNaN(from) ? 0
: from
< 0 ? Math.ceil(from) + len : Math.floor(from);

for ( ; from < len; from++ ) { if ( array[from] === elt ) return from; }
return -1;
}
},
lastIndexOf:
function( array, elt, from ){
if (array.lastIndexOf) {
return isNaN(from) ? array.lastIndexOf(elt) : array.lastIndexOf(elt, from);
}
else {
var len = array.length;
from
= isNaN(from) || from >= len - 1 ? len - 1
: from
< 0 ? Math.ceil(from) + len : Math.floor(from);

for ( ; from > -1; from-- ) { if ( array[from] === elt ) return from; }
return -1;
}
}
};

function each( object, callback ) {
if ( undefined === object.length ){
for ( var name in object ) {
if (false === callback( object[name], name, object )) break;
}
}
else {
for ( var i = 0, len = object.length; i < len; i++ ) {
if (i in object) { if (false === callback(object[i], i, object )) break; }
}
}
};

each({
forEach:
function(object,callback,thisp){
//大家看一下为什么上面的each函数,没有用this指针,这里还要用each.call,牛人请指点???
each.call(thisp, object, function(){ callback.apply(thisp, arguments); } );
},
map:
function( object, callback, thisp ){
var ret = [];
each.call( thisp, object,
function(){ ret.push(callback.apply(thisp, arguments)); });
return ret;
},
filter:
function( object, callback, thisp ){
var ret = [];
each.call( thisp, object,
function(item){
callback.apply(thisp, arguments)
&& ret.push(item);
});
return ret;
},
every:
function( object, callback, thisp ){
var ret = true;
each.call( thisp, object,
function(){
if ( !callback.apply(thisp, arguments) ){ ret = false; return false; };
});
return ret;
},
some:
function( object, callback, thisp ){
var ret = false;
each.call( thisp, object,
function(){
if ( callback.apply(thisp, arguments) ){ ret = true; return false; };
});
return ret;
}
},
function(method, name){
ret[name]
= function( object, callback, thisp ){
if (object[name]) {
return object[name]( callback, thisp );
}
else {
return method( object, callback, thisp );
}
}
});

return ret;
}();

 

ForFreeDom的主页 ForFreeDom | 小虾三级 | 园豆:589
提问于:2010-03-21 12:40
< >
分享
最佳答案
0

没有啥意义,大概只是为了防止each的实现啥时候改成用到this指针吧

收获园豆:15
Gray Zhang | 专家六级 |园豆:17610 | 2010-03-22 14:29
其他回答(1)
0

这个东西说实在的看的不是非常明白,这里有点像Prototype中的一些扩展。个人看你说的那个地方调用call,貌似是javascript中call的原生用法。

收获园豆:5
西越泽 | 园豆:10775 (专家六级) | 2010-03-22 10:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册