call aplly方法的作用相同,区别仅在于接收参数的方式不同。
call 传递参数是一一列举。
apply 是以数组的方式传递参数列表。
参数传递方式的不同并不是这两个方法的真正意义所在。改变函数运行的作用域才是他们真正的战场。

window.color = 'red'
var o = {color: 'yellow'}
function showColor() {
    console.log(this.color)
}
showColor() // red
showColor.call(window)  // red
showColor.call(this)  // red
showColor.call(o)   // yellow

this 默认指向 window
call 可以修改 this 的指向

相当于:

showColor.call(o)
// 它等价于
o.showColor()
// 那么也就是说
o.showColor = showColor // 把 showColor 写为 o 的一个方法
o.showColor()  // 然后执行这个方法
delete o.showColor // 调用完毕将这个方法删除

那就可以模拟实现一下:

showColor.newCall(o) // yellow
Function.prototype.newCall = function(ctx){
  ctx.fn = this // 谁调用了这个newCall, this 指向谁(showColor)
  ctx.fn() // 执行
  delete ctx.fn
}

改变 this 指向完成了
接下来的事情就是考虑参数怎么处理

var o = {color: 'yellow'}

function showColor(a, b){
    console.log(this.color);
    return {
        a: a,
        b: b
    }
}

Function.prototype.newCall = function(){
    var args = []
    ctx = arguments[0] || window
    ctx.fn = this // 谁调用了这个newCall, this 指向谁(showColor)
    for (var i = 1; i < arguments.length; i ++){
        args.push('arguments[' + i + ']')
    }
    var res = eval('ctx.fn(' + args.join(',') + ')')
    delete ctx.fn
    return res
}

showColor.newCall(o, 'red', 'blue')

那么自定义的newApply也好实现了, 只是传递参数的方式不同而已

Function.prototype.newApply = function(ctx, arr){
    ctx = ctx || window
    ctx.fn = this // 谁调用了这个newCall, this 指向谁(showColor)
    var res;
    if(!arr){  // 没有参数
        res = ctx.fn()
    } else {
        var args = []
        console.log(arr);
        for (var i = 0; i < arr.length; i ++){
            args.push('arr[' + i + ']')
        }
        res = eval('ctx.fn(' + args.join(',') + ')')
    }
    delete ctx.fn
    return res
}