当前位置:首页 » 《随便一记》 » 正文

JavaScript之手撕call、apply_战场小包的博客

2 人参与  2022年02月26日 08:19  分类 : 《随便一记》  评论

点击全文阅读


前言

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;
}

点击全文阅读


本文链接:http://zhangshiyu.com/post/35369.html

数组  函数  方法  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1