JavaScript之手撕call、apply

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 +‘)’)

跳槽是每个人的职业生涯中都要经历的过程,不论你是搜索到的这篇文章还是无意中浏览到的这篇文章,希望你没有白白浪费停留在这里的时间,能给你接下来或者以后的笔试面试带来一些帮助。

也许是互联网未来10年中最好的一年。WINTER IS COMING。但是如果你不真正的自己去尝试尝试,你永远不知道市面上的行情如何。这次找工作下来,我自身感觉市场并没有那么可怕,也拿到了几个大厂的offer。在此进行一个总结,给自己,也希望能帮助到需要的同学。

面试准备

面试准备根据每个人掌握的知识不同,准备的时间也不一样。现在对于前端岗位,以前也许不是很重视算法这块,但是现在很多公司也都会考。建议大家平时有空的时候多刷刷leetcode。算法的准备时间比较长,是一个长期的过程。需要在掌握了大部分前端基础知识的情况下,再有针对性的去复习算法。面试的时候算法能做出来肯定加分,但做不出来也不会一票否决,面试官也会给你提供一些思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值