手写call、apply、bind函数

本文章用于个人笔记-内容参考于掘金

  • 先看一下callapplybind的应用
function a(key,value){
  console.log(this.name)
  console.log(key)
  console.log(value)
}
var name = 'lv'
var obj = {
  name: 'yong'
}
a.call(obj,1,2)//'yong' 1 2
a.call(obj)//'yong' undefined undefined
a.apply(obj,[1,2])//'yong' 1 2
var b = a.bind(obj,1,2)
b()//'yong' 1 2
  • 手写实现-call
Function.property.myCall = function(context){
  if(typeof this != 'function'){
    return throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  let args = context.slice(1)
  const result = context.fn(...arg)
  delete context.fn
  return result
}

-手写实现-apply

Function.prototype.myApply = function(context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  let result
  // 处理参数和 call 有区别
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}
  • 手写实现-bind
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  const _this = this
  const args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容