如何修复我的js绑定实现?

时间:2018-06-25 02:03:05

标签: javascript function bind

我正在准备面试,并想编写自己的JS绑定功能实现。我正在引用此polyfill代码:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

测试又回来了

 Expected value to equal:
      42
 Received:
      undefined

感谢您帮助我们识别bind2函数的问题,以及是否可以描述如何调试引用此函数的函数?

要点:https://gist.github.com/Falieson/580e4feb26e92ece7d93b102c78a6f76

bind2.ts函数

// tslint:disable no-any

export default function bind2(this: any, that: any) {
  const f = this // tslint:disable-line no-this-assignment
  const initialArgs = Array.prototype.slice.call(arguments, 1)

  return (finalArgs: any[]) => f.apply(that, [...initialArgs, ...finalArgs])
}

bind2.test.ts

// tslint:disable no-any
import bind2 from '../bind2'

function decorate(obj: any): any {
  const res = new Function()
  Object.assign(res, obj)
  res['bind2'] = bind2 // tslint:disable-line no-string-literal
  return res
}

describe('.bind2(target)', () => {
  test('works', () => {
    const data = {
      getX() {
        return this.x
      },
      x: 42,
    }
    const unboundGetX = data.getX
    const boundGetX = decorate(unboundGetX).bind2(data)

    expect(boundGetX()).toEqual(42)
  })
})

1 个答案:

答案 0 :(得分:1)

您将that设置为this的{​​{1}},但是boundGetX()参数是that

undefined