likes
comments
collection
share

JavaScript面试之手写call、apply、bind

作者站长头像
站长
· 阅读数 48

面试初始

近期准备跳槽,所以投递了不少中大公司,有几家都要求线上面试手写代码,出现概率最多的就是手写callapplybind,今天就分享一下这三个函数的基本实现。

实现代码

call的实现

Function.prototype.call = function(context,...args) {
  context = context || window // 判断上下文是否传入,默认window
  const fn = this // 保存this

  context.fn = fn // 最重要的一步:改变this指向,通过挂载到context上,实现this的转移
  const res = context.fn(...args) // 立即执行
  
  delete context.fn

  return res // 返回结果
}

apply的实现

Function.prototype.apply = function(context,...args) {
	context = context || window // 判断上下文是否传入,默认window
  	const fn = this // 保存this

  	context.fn = fn // 最重要的一步:改变this指向,通过挂载到context上,实现this的转移
  	const res = context.fn(...args[0]) // 立即执行
    
    delete context.fn

  	return res // 返回结果
}

bind实现

bind的方法和applycall稍微有所不同,bind是一个闭包结构,返回的是一个函数,函数内还是正常调用call方法即可

Function.prototype.bind = function(context,...args) {
	context = context || window // 判断上下文是否传入,默认window
    const fn = this // 保存this
    
    context.fn = fn // 最重要的一步:改变this指向,通过挂载到context上,实现this的转移
    
    // 返回闭包
    return function() {
    	const res = context.fn(...args) // 立即执行
        
    	delete context.fn
        
        return res // 返回结果
    }
}

总结

以上就是这次面试的部分试题,手写代码貌似已经是大部分公司必考的一个步骤,后期会继续分享面试中的一些试题,希望大家都能拿到心怡的offer。

转载自:https://juejin.cn/post/6884918595541794829
评论
请登录