美文网首页海纳百川
手写call、apply、bind函数

手写call、apply、bind函数

作者: 凛冬已至_123 | 来源:发表于2019-09-27 10:05 被阅读0次

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

  • 先看一下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))
  }
}

相关文章

  • JS进阶知识点和常考面试题

    手写 call、apply 及 bind 函数 涉及面试题:call、apply 及 bind 函数内部实现是怎么...

  • 前端---请你手写一个XXX吧

    目录 手写 call、apply、bind函数 手写去抖和节流两个通用函数

  • 手写call bind apply

    手写call bind apply

  • call(),apply()和bind()

    call、apply和bind函数存在的区别:bind返回对应函数, 便于稍后调用; apply, call则是立...

  • apply, call, bind

    apply, call, bind 都是用来改变函数的this对象的指向 apply, call, bind 第一...

  • bind call apply

    区别:call和apply调用就是执行函数 bind返回新函数 bind利用call或apply兼容i...

  • this_原型链_继承

    问题1: apply、call 、bind有什么作用,什么区别 bind,apply,call:都是返回一个函数,...

  • this_原型链_继承

    问题1: apply、call 、bind有什么作用,什么区别 apply ,call,bind都会改变函数的执行...

  • this

    1、apply、call 、bind有什么作用,什么区别? apply、call 、bind都被用来改变函数的th...

  • call,apply,bind区别与实现

    区别: 指定this,call和apply执行函数,bind不执行 call,apply,bind都是为了解决th...

网友评论

    本文标题:手写call、apply、bind函数

    本文链接:https://www.haomeiwen.com/subject/yxmsyctx.html