编辑代码

Array.prototype.myMap = function(fn,context){
    let arr = Array.prototype.slice.call(this)
   
    let mapArr = []
    for(let i=0;i<arr.length;i++){
        mapArr.push(fn.call(context,arr[i],i,this))
    }
    return mapArr
}

var test = [1,2,3,4]
//console.log(test.map(item=>item*2))

//手写实现call
//1.判断当前this是否为函数,防止Function.prototype.myCall直接调用
//2.context为默认参数,不传的话默认上下文为window
//3.为context创建一个Symbol属性,将当前函数赋值给该属性
//4.处理参数,传入第一个参数后的剩余参数
//5.调用函数后删除该Symbol属性
Function.prototype.myCall = function(context=window,...args){
    if(this===Function.prototype){
        return undefined
    }
    context = context||window
    const fn = Symbol()
    context[fn] = this
    const result = context[fn](...args)
    delete context[fn]
    return result
}

Function.prototype.myApply = function(context=window,args){
    if(this===Function.prototype){
        return undefined
    }
    context = context||window
    const fn = Symbol()
    context[fn] = this
    let result
    if(Array.isArray(args)){
        result = context[fn](...args)
    }else{
        result = context[fn]()
    }
    
    delete context[fn]
    return result
}