JavaScript——函数的call、apply、bind方法

发布时间 2024-01-05 17:44:32作者: 周祥宇

JavaScript的函数拥有三个方法:

  1. call
  2. apply
  3. bind

这三个方法都可以改变函数被调用时,函数内部this的指向。至于区别,阅读下面代码即可一目了然:

function myCall(context) {
    const args = [...arguments].slice(1)
    let result

    context = context ? context : window
    context[Symbol.for('myCall')] = this
    result = context[Symbol.for('myCall')](...args)
    delete context[Symbol.for('myCall')]

    return result
}

function myApply(context, args) {
    args = args ? args : []

    return this.myCall(context, ...args)
}

function myBind(context) {
    const that = this,
        args = [...arguments].slice(1)

    context = context ? context : window

    return function () {
        return that.myApply(context, args.concat(...arguments))
    }
}

Function.prototype.myCall = myCall
Function.prototype.myApply = myApply
Function.prototype.myBind = myBind

由代码可知,它们的区别如下:

  1. call、apply会立即在指定的执行上下文中执行函数并返回执行结果;bind会返回一个已指定执行上下文的函数但并未执行
  2. call被调用时,参数可以一个一个地直接传;apply被调用时,参数需封装成一个数组再传;bind被调用时,参数可以分开传

欢迎评论,欢迎纠错,我们一起成长!
xyzh.work@foxmail.com