is there a way to bind `this` in an arrow function without having to use eval?

Viewed 21

is there a way to bind this in an arrow function without having to use eval?

I had to write a function that takes a callback and a context where that callback is bound. It should work even when the callback passed is an arrow function. Something like this

myFunction(() => {
  console.log(this.name) // this should log out 'foo'
}, {name: 'foo'})

My solution is to use eval to convert the arrow function (i.e. the callback) into a normal function:

const obj = { name: 'lol' }

const arrowFn = () => this.name

function bindArrowFn(fn, context) {
  return function () {
    return eval(Function.prototype.toString.call(fn))
  }.apply(context)
}

const boundArrowFn = bindArrowFn(arrowFn, obj)
boundArrowFn() // 'lol' ✅

This works but I wonder if this is the only way we can do this? Is there a way to avoid using eval?

0 Answers
Related