美文网首页
如何理解函数的apply, call, bind方法

如何理解函数的apply, call, bind方法

作者: 暮云春树_3126 | 来源:发表于2019-02-27 18:10 被阅读0次

1.apply

在特定的作用域中调用该函数,并设置函数内的this对象的值(传入的第一个参数)函数的实参(传入的第二个参数,可以是 Array 的实例,也可以是arguments 对象)

使用场景:当我们在类数组对象上调用数组的方法。

function someFnc () {
// 把arguments当成数组,并调用数组原型上的forEach方法去遍历它
  Array.prototype.forEach.apply(arguments, [
    function (item, index) {
    // do something
    }
  ])
}
// 需要注意的是,我们调用apply方法传入的第二个参数必须为数组对象或arguments对象

2.call

call的作用与apply是一样的,区别在于接收参数的方式,第一个参数没有变化,其余的必须逐个传入。

// 可以看出我们将forEach函数需要的参数直接传入的。
Array.prototype.forEach.apply(arguments, function (item, index) {
      // do something
  }
)

3. bind

bind创建一个函数的实例,并将其内部的this值设置为传入的第一个参数,其余的参数为实例的默认实参,会排在最前面。
我们可以用apply去实现bind方法

Function.prototype.bind = function () {
  let args = Array.prototype.slice.apply(arguments)
  let  that = this
  if (typeof args[0] === 'undefined') {
    return that
  }
  return function () {
    let args1 = Array.prototype.slice.apply(arguments)
    return that.apply(args[0], args.slice(1).concat(args1))
  }
}

相关文章

网友评论

      本文标题:如何理解函数的apply, call, bind方法

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