Falieson
Falieson

Reputation: 2556

How to fix my implementation of js bind?

I'm prepping for interviews and wanted to write my own implementation of the JS bind function. I am referencing this polyfill code: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

The test comes back

 Expected value to equal:
      42
 Received:
      undefined

Thank you for your help in identifying the issue with the bind2 function, and if you could describe how you would debug a function that references this?

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

the bind2.ts function

// 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])
}

the 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)
  })
})

Upvotes: 2

Views: 66

Answers (1)

joaner
joaner

Reputation: 716

You set that as this of boundGetX(), but that param is undefined.

export default function bind2(data: any) {
  const initialArgs = Array.prototype.slice.call(arguments, 1)

  return (finalArgs: any[]) => this.apply(data, [...initialArgs, ...finalArgs])
};

function decorate(obj: any): any {
  obj.bind2 = bind2
  return obj
}

Upvotes: 1

Related Questions