window._ = {
VARSION:"0.1.0",
each:function(obj,iterator,context){
var index = 0;
try{
if(obj.forEach){
obj.forEach(iterator,context);
}else if(obj.length){
for( var i= 0; i<obj.length; i++){
iterator.call(context,obj[i],i);
}
}else if(obj.each){
obj.each(function(value){
iterator.call(context,value,index++)
});
}else{
var i = 0;
for(var key in obj){
var value = obj[key],
pair = [key,value];
pair.key = key;
pair.value = value;
iterator.call(context,pair,i++);
}
}
}catch(e){
console.log(e)
// if(e != "__break__") throw e;
}
return obj;
}
}
var arr = {
a:5,
b:6,
c:4
}
_.each(arr,function(a,b){
console.log(a)
console.log(b)
})
Img cannot be uploaded due to network speed. Sorry
I want to know the specific function of that call in this code.
What is the execution process? Thank you all
The scope of
call
是为了给你保证你提供了第三个参数的时候callback
is not polluted.The execution order of the code can be debug
iterator.call(context...
is equivalent to binding this to the iterator function as context
iterator.call()
中,iterator
is the traversal function passed in. In this case, it refers to the anonymous function:Therefore, call refers to
The signature format ofFunction.prototype.call
. For details, see Function.prototype.call() - JavaScript | MDNFunction.prototype.call
is:thisArg is used to change the binding of the
this
pointer inside the function.Used to specify the execution environment of the function
call makes this of the specified function point to the corresponding object.
The above example:
iterator.call(context,obj[i],i)//this points to context, obj[i],i is the parameter
It is recommended to read it to understand the above code http://www.liaoxuefeng.com/wi...