天天看点

JavaScript之手撕call、apply

前言

call/apply

的核心理念就是借用方法。

这话乍一听上去,感觉有点云里雾里。讲一个生活中的实例来描述一下:

老邓和老王是邻居,老邓家有火锅,老王家有烧烤架。老王家很少吃火锅,但突然有一天想吃火锅,他就可以去老邓家借用火锅,这样老王家不仅吃上了火锅,还没花买锅的钱。同样如果有一天老邓家想吃烧烤,便可以去老王家借烧烤架。

call/apply

做的便是类似的事,

A

对象上实现了一个方法,

B

对象由于一些需求,也需要调用同样的方法,最好的方法肯定是

B

直接去调用

A

对象的方法,自身无需扩展。

基本介绍

语法:

fn.call(thisArg, arg1, arg2,...)
fn.apply(thisArg, [arg1, arg2,...])
           

参数

  • thisArg

    (可选):
    • fn

      函数的

      this

      指向

      thisArg

    • thisArg

      传入

      null,undefined

      :非严格模式下:fn函数

      this->window

      ;严格模式:

      this->undefined

    • 值为原始值(数字,字符串,布尔)时,this指向包装类
  • arg1,arg2

    (可选): 传给fn的参数
    • apply传递的第二个参数为数组

作用

改变

this

指向

常见用法

  1. 判断数据类型:

    typeof

    方法只返回七种值:

    string、number、boolean、undefined、object、function、symbol

    。所以使用

    typeof

    是无法区分

    array

    和普通对象的。
arr = []
typeof(arr)  // "object"
obj = {}
typeof(obj)  // "object"
           

Object.prototype.toString

方法可以判断所有的类型,但

Array、String

等都重写了该方法,因此就需要借助

call/apply

来实现

Object.prototype.toString.call(arr) // "[object Array]"
Object.prototype.toString.call(obj) // "[object Object]"
           
  1. 类数组调用数组的方法

    ES6

    未发布之前,没有

    Array.from

    方法可以将类数组转为数组,采用

    Array.prototype.slice.call(arguments)

    [].slice.call(arguments)

    将类数组转化为数组。

当然别的数组方法也可以类似调用,例如

push

方法:

var arraylike = {
    0: 1,
    length: 1
}
Array.prototype.push.call(arrlike, 1) // {0: 1, 1: 2, length: 2}
           
  1. apply

    求数组的最大值与最小值

    JavaScript中没有给数组提供类似max和min函数,只提供了

    Math.max/min

    ,用于求多个数的最值,所以可以借助apply方法,直接传递数组给

    Math.max/min

const arr = [1,10,11,33,4,52,17]
Math.max.apply(Math, arr)
Math.min.apply(Math, arr)
           

手撕call

初步模拟

首先看一个简单例子,分析一下

call

函数执行过程:

var obj = {
    value: 1
}
function fun() {
    console.log(this.value)
}
fun.call(obj) // 1
           

可见

call

函数调用大致执行了两部:

  • call

    改变了

    this

    指向,

    this->obj

  • fun

    函数执行

那该如何模拟上面的效果那?如果在obj上定义函数fun,之后obj.fun执行是不是就达成了上述的效果。

所以

call

的模拟步骤大约是:

  • 将函数

    fn

    设为

    thisArg

    的对象的方法
  • 执行

    thisArg.fn

  • 删除该函数
Function.prototype.myCall = function (thisArg) {
    // this为调用myCall的函数
    thisArg.func = this;
    thisArg.func();
    delete(thisArg.func);
}
           

完善

上面实现了

call

的最初版代码,还有几个地方有待解决:

  1. 未传入

    thisArg

    参数:当未传入

    thisArg

    或传入

    null

    时,函数的

    this->window

thisArg = thisArg || window
           
  1. 传入

    arg1,arg2

    等参数:ES6可以通过

    rest

    参数来实现,ES6以前可以通过

    arguments

    来实现
// ES5
const args = []
for (let i = 1; i<arguments.length; i++) {
    args.push('argumens['+ i + ']')
}
eval('thisArg.func(' + args +')')
           
  • eval()

    函数计算

    JavaScript

    字符串,并把它作为脚本代码来执行。
  • array

    在与字符串相加时,会调用

    array.toString

    方法(

    [1,2,3].toString() // "1,2,3"

    )。
  • 函数可以拥有返回值

    举个例子:

const obj = {
    value: 1
}
function func(name, age) {
    return {
        name,
        age,
        value: this.value
    }
}
func.call(obj, 'zcxiaobao', 24)
// {
//     age: 24,
//     name: "zcxiaobao",
//     value: 1,
// }
           

不过很好解决,因此只需将eval执行之后的结果返回即可。

接着我们来看一下完整版的代码:

Function.prototype.myCall = function (thisArg) {
    thisArg = thisArg || window;
    thisArg.func = this;
    const args = []
    for (let i = 1; i<arguments.length; i++) {
        args.push('arguments['+ i + ']')
    }
    const result = eval('thisArg.func(' + args +')')
    delete thisArg.func;
    return result;
}
           

如果使用ES6语法进行模拟代码会简单很多

Function.prototype.myCall = function (thisArg, ...args) {
    thisArg = thisArg || window;
    thisArg.func = this;
    args = args || []
    const result = thisArg.func(..args)
    delete thisArg.func;
    return result;
}
           

手撕apply

apply

的代码实现与

call

类似,这里直接给代码。

Function.prototype.myApply = function (thisArg, arr) {
    thisArg = thisArg || window;
    thisArg.func = this;
    const args = []
    for (let i = 0; i<arr.length; i++) {
        args.push('arr['+ i + ']')
    }
    const result = eval('thisArg.func(' + args +')')
    delete thisArg.func;
    return result;
}
           

继续阅读