简单实现call,bind,apply,🍄掌握其思路

166 阅读1分钟

image.png

场景⛱

  • 面试官🤵提问:“ 能不能简单实现call,bind,apply?”

  • 求职者🙍‍♂️:“没问题!”

  • 面试官 🤵:“来吧,展示”

一、call方法实现

思路🚩

  1. 接受多个参数,第一个为上下文,第二个及以后为函数本身参数
  2. 判断是否传入this
  3. 改变this指向
  4. 执行函数得到结果
  5. 删除this,避免全局污染

call简易代码🚀(Symbol,解构赋值)

Function.prototype.call1 = function (_this,...arg) {
    const c = Symbol('c')
    _this = _this||window //判断_this
    _this[c] = this
    const result = _this[c](...arg)
    delete _this[c]
    return result
}

二、apply方法实现

思路🚩🚩

  1. 接受多个参数,第一个为上下文,第二个为函数本身参数(数组)
  2. 判断是否传入this
  3. 改变this指向
  4. 执行函数得到结果
  5. 删除this,避免全局污染

apply简易代码🚀(Symbol,解构赋值)

Function.prototype.apply1 = function (_this,arg) {
    const a = Symbol('a')
    _this = _this||window //判断_this
    _this[a] = this
    const result = _this[a](...arg)//执行函数,获取结果
    delete _this[a]
    return result
}

三、bind方法实现

思路🚩🚩🚩

  1. 继承原型
  2. 更改this
  3. 合并argument并传递

bind简易代码🚀(instanceof,slice,concat)

Function.prototype.bind1 = function (_this,arg) {
    const that = this
var fn = function () {
    that.apply(this instanceof that?this :_this,arg.concat(Array.prototype.slice.call(arguments)))//slice返回一个新的数组
}
    fn.prototype = that.prototype//继承原型
    return fn
}

小结🎖

  • 都是改变this的指向,要注意它们之间的区别
  • 在改变this指向的同时也要注意argument的处理

点赞支持👍