javascript - js call execution process
迷茫
迷茫 2017-05-19 10:37:03
0
5
564
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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(5)
習慣沉默

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

伊谢尔伦

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:

function(a, b) { console.log(a); console.log(b); }

Therefore, call refers to Function.prototype.call . For details, see Function.prototype.call() - JavaScript | MDN

The signature format of

Function.prototype.call is:

func.call(thisArg, param1, param2, ...)

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...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template