0

using the bind documentation, if i replace the object (defined as module in their example), with an es6 class instance, it does not bind.

here are the docs... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

and here is my code...

class Foo {}
let foo = new Foo()

let fooVar = 'foo var'
let fooFunc = () => {
  return this.var
}

foo['var'] = fooVar
fooFunc.bind(foo)
foo['func'] = fooFunc

// i expected this to return 'foo var', but instead get 'undefined'
foo.func()

how can i essentially add an instance method to an existing instance, and have it bind properly?

brewster
  • 4,342
  • 6
  • 45
  • 67
  • 3
    you can't bind arrow functions - also just having `fooFunc.bind(foo)` throws away the newly bound function anyway – Jaromanda X Oct 06 '20 at 07:41
  • gah! i thought arrow functions were just syntactic sugar... also, even without assigning the bound function directly, it still works. the arrow function was the only problem... – brewster Oct 06 '20 at 07:47

1 Answers1

1

If you read the documentation about arrow function you will see that:

Does not have its own bindings to this or super, and should not be used as methods.

Therefore you cant bind a new this if it doesnt have one

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • gotcha! so, this logic is part of a developer api, and if developers don't know about this rule like i didn't, is there a way i can convert their arrow function into a normal function somehow, or bind `this` to their arrow function? – brewster Oct 06 '20 at 07:54
  • @brewster you mean like this `fooFunc() { return this.var }` ? – bill.gates Oct 06 '20 at 07:56
  • essentially yeah... if a developer passes in an arrow function to my api, can i modify their arrow function to allow `this` to work as expected? or do i just need to be explicit in my documentation? :) – brewster Oct 06 '20 at 08:00