javascript之call和apply的模拟实现

102 阅读2分钟

call

定义

call() 方法在使用一个指定的 this 值和若干个指定的参数值的前提下调用某个函数或方法。

// 使用方式
func.call(thisArg, arg1, arg2,...)

作用

  1. 改变了函数活动对象this的指向,指向新对象thisArg
  2. 之后执行该函数

举个例子:

var obj = {
    value: 1
}

function bar() {
    console.log(this.value)
}

bar.call(obj) // 1

这里:

  1. call 改变了this指向,指到obj
  2. bar函数执行了

那么我们可以把模拟的步骤分为以下三步:

  1. 将函数设为对象的属性
  2. 执行该函数
  3. 删除该函数
// 1.
obj.fn = bar
// 2.
obj.fn()
// 3.
delete obj.fn

模拟实现第一版call2

根据这思路,我们可以写出第一版的call2函数:

Function.prototype.call2 = function(context) {
    context.fn = this
    context.fn()
    delete context.fn
}

//测试
var obj = {
    value: 1
}

function bar() {
    console.log(this.value)
}

bar.call2(obj) // 1

模拟实现第二版call2

根据定义我们知道call可以接收除this参数之外的其他参数, 参数个数不固定我们可以从arguments取出除第一个外的所有参数,然后放到数组里。

Function.prototype.call2 = function(context) {
    context.fn = this
    const args = []
    // 取出参数
    for(let i = 1; i < arguments.length; i++) {
        args.push('arguments['+i+']')
    }
    // 执行后 args为 ["arguments[1]", "arguments[2]", "arguments[3]"]
    //args 会自动调用 Array.toString() 这个方法
    eval('context.fn('+args+')')
    delete context.fn
}

//测试
var obj = { 
    value: 1
}

function bar(name, age) {
    console.log(name, age, this.value)
}

bar.call2(obj, '李四', 12) // '李四'  12  1

模拟实现第三版call2

再补充些小细节

  1. this参数可以传入null, 这时指向window对象呢
  2. 函数可以有返回值 于是我们得到下面的代码:
Function.prototype.call2 = function(context) {
    context = context || window
    context.fn = this
    const args = []
    // 取出参数
    for(let i = 1; i < arguments.length; i++) {
        args.push('arguments['+i+']')
    }
    //args 会自动调用 Array.toString() 这个方法
    const result = eval('context.fn('+args+')')
    // 使用es6
    // const result = context.fn(...args)
    delete context.fn
    return result
}

//测试
var obj = { 
    value: 1
}

function bar(name, age) {
    return {
        name, 
        age, 
        value: this.value
    }
}

const res = bar.call2(obj, '李四', 12) 
//res = {name: '李四',age:12,value:1}

到这里就完成call的模拟实现了! 给自己点个赞^_^

apply的实现和call类似,下面直接贴代码。

apply

apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。

func.apply(thisArg, [argsArray])

apply的模拟实现

Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window
    context.fn = this
    var result
    if (!arr) {
        result = context.fn()
    } else {
        // es5
        var args = []
        // 循环取'arr['+i+']' 是为了不让eval解析的时候,把变量值解析变量
        for(let i = 0; i < arr.length; i++) {
            args.push('arr['+i+']')
        }
        result = eval('context.fn(' + args + ')')
        
        // es6
        // result = context.fn(...arr)
    }

    delete context.fn
    return result;
}