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
習慣沉默2017-05-19 10:39:03
The scope of
call
是为了给你保证你提供了第三个参数的时候 callback
is not polluted.
_.each(arr, function (a, b) {
console.log(this); //window
})
_.each(arr, function (a, b) {
console.log(this); // arr
},arr)
The execution order of the code can be debug
伊谢尔伦2017-05-19 10:39:03
iterator.call(context...
is equivalent to binding this to the iterator function as context
漂亮男人2017-05-19 10:39:03
iterator.call()
中,iterator
is the traversal function passed in. In this case, it refers to the anonymous function:
function(a, b) { console.log(a); console.log(b); }
Therefore, call refers to Function.prototype.call
. For details, see Function.prototype.call() - JavaScript | MDN
Function.prototype.call
is:
func.call(thisArg, param1, param2, ...)
thisArg is used to change the binding of the this
pointer inside the function.
阿神2017-05-19 10:39:03
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...