apply的模拟实现

咱们知道call和apply方法的做用基本同样,主要的区别在于第二个参数的传递,call直接传递参数便可,apply的须要传递一个参数列表。
所以call和apply的实现原理基本相同,能够参考https://segmentfault.com/a/11...
这样咱们就直接上最终版的实现代码,以下segmentfault

Function.prototype.apply2 = function (context, arr) {
    context = context || window
    var args = []
    //遍历参数列表中的数据而后添加到args数组中
    for (var i = 0; i < arr.length; i++) {
        args.push('arr[' + i + ']')
    }
    // 在obj对象中添加fn属性,而且fn的值为函数bar
    context.fn = this
    // 执行fn方法,并返回值
    const result = eval('context.fn(' + args + ')')
    // 执行fn方法结束后,删除添加到obj中的fn方法
    delete context.fn
    return result
}
var obj = {
    value: 1
}
function bar(name, age) {
    console.log(name, age)
    return {
      value: this.value,
      name,
      age
    }
}
console.log(bar.apply2(obj, ['张三', 18]))

使用ES6方法实现以下数组

Function.prototype.apply2 = function (context, arr) {
    context = context || window
    let fn = Symbol()
    context.fn = this
    const result = context.fn(...arr)
    delete context.fn
    return result
}
var obj = {
    value: 1
}
function bar(name, age) {
    console.log(name, age)
    return {
      value: this.value,
      name,
      age
    }
}
console.log(bar.apply2(obj, ['张三', 18]))
相关文章
相关标签/搜索