寫個apply

Function.prototype.myApply = function(context,arr){
    context = context || window;//如果是null,或者爲空,則指向window
    context.fn = this;//獲取到調用的方法
    
    var result;
    if(!arr){//沒有傳參
        result =  context.fn();
    }else{
        var args = [];
        for(var i = 0;i < arr.length; i++){ //注意 i 從0開始
            args.push('arr['+i+']');
        }
        result = eval('context.fn('+args+')');
    }

    delete context.fn;
    return result;
}

參考:https://github.com/mqyqingfeng/Blog/issues/11

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章