一 写前需要先了解一下他们的用法

call 和 apply 是为了动态改变 this 而出现的.传入call的参数只能是单个参数,不能是数组。apply可传入数组。

区别

func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
    Function.prototype.call1 = function (context) {
        var context = context || window;
        context.fn = this
        let args = [...arguments].slice(1)
        let result = context.fn(...args)
        delete context.fn
        return result
    }

apply

    Function.prototype.apply1 = function (context) {
        var context = context || window;
        context.fn = this;
        let args = arguments[1]
        let result;
        if (args) {
            result = context.fn(...args)
        } else {
            result = context.fn()
        }
        delete context.fn
        return result
    }

bind

暂无

测试

    var name = '呵呵'
    var foo = {
        name: '嘿嘿',
    }

    function bar(a, b, c) {
        return {
            name: this.name,
            a,
            b,
            c
        }
    }

    console.log(bar.call1(foo, 11, 12, 13))
    console.log(bar.apply1(foo, [11, 12, 13]))
    console.log(bar.bind1(foo, 11))

 

相关文章:

  • 2021-12-31
  • 2021-09-21
  • 2021-07-11
  • 2021-08-27
  • 2022-03-08
  • 2021-09-19
  • 2022-01-05
猜你喜欢
  • 2021-05-16
  • 2022-12-23
  • 2022-01-31
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
相关资源
相似解决方案