JavaScript 实现Bind方法

Posted 乱舞春秋__

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 实现Bind方法相关的知识,希望对你有一定的参考价值。

实现Bind 方法

关键步骤

  1. 获取调用bind方法的函数
      const f = this
  1. 获取bind方法的this参数和其他参数
      const args = [...arguments]
      const thisValue = args.shift()
  1. 返回函数
      return function () {
        return f.apply(thisValue, args)
      }

完整代码

   Function.prototype.myBind = function () {
      const f = this
      const args = [...arguments]
      const thisValue = args.shift()
      return function () {
        return f.apply(thisValue, args)
      }
    }

示例

    //定义 test 函数
    function test (a, b) {
      return [this, a + b]
    }
    const result = test(1, 2)
    console.log(result) // [Window, 3]
	
	// test 函数调用 myBind 方法
    const _test = test.myBind({a: 1}, 2, 3)
    const _result = _test()
    console.log(_result) // [{ a: 1 }, 5]

以上是关于JavaScript 实现Bind方法的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 实现Bind方法

JavaScript 实现Bind方法

JavaScript 实现Bind方法

Javascript中bind()方法的使用与实现

[Effective JavaScript 笔记]第26条:使用bind方法实现函数的柯里化

javaScript原生bind方法的详细解析!