call, apply, bind 区别

call, apply, bind 区别
首先说下前二者的区别。
call 和 apply 都是为了解决改变 this 的指向。做用都是相同的,只是传参的方
式不一样。
除了第一个参数外,call 能够接收一个参数列表,apply 只接受一个参数数组。
let a = {
    value: 1
}
function getValue(name, age) {
26
前端面试指南
    console.log(name)
    console.log(age)
    console.log(this.value)
}
getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])
模拟实现 call 和 apply
能够从如下几点来考虑如何实现
不传入第一个参数,那么默认为 window
改变了 this 指向,让新的对象能够执行该函数。那么思路是否能够变成给新的对
象添加一个函数,而后在执行完之后删除?
Function.prototype.myCall = function (context) {
  var context = context || window
  // 
给
 context 
添加一个属性
  // getValue.call(a, 'yck', '24') => a.fn = getValue
  context.fn = this
  // 
将
 context 
后面的参数取出来
  var args = [...arguments].slice(1)
  // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
  var result = context.fn(...args)
  // 
删除
 fn
  delete context.fn
  return result
}

 

以上就是 call 的思路,apply 的实现也相似

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this
  var result
  // 
须要判断是否存储第二个参数
  // 
若是存在,就将第二个参数展开
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}

 

bind 和其余两个方法做用也是一致的,只是该方法会返回一个函数。而且咱们可

以经过 bind 实现柯里化。
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var 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))
  }
}
相关文章
相关标签/搜索