0

I have the following object:

const person={
   name: 'jordan',
   greet: function(){console.log('hello, ' + this.name)}
}

I know I can do the following:

const greet = person.greet.bind(person)

I'm trying to bind person using arrow notation. Is it possible?

I thought maybe

const greet = person.greet(()=>(person.greet))

or

const greet = person.greet(()=>(function(){person.greet}))

but both of those give immediate execution and greet remains undefined

DCR
  • 14,737
  • 12
  • 52
  • 115
  • that's true, I can go person.greet() but I want to define a const called greet and be able to greet() with this being bound to person. I can do this without using => and was wondering how to do it with => – DCR Mar 31 '18 at 22:24
  • 2
    @GeorgeJempty actually, he does need bind. When you pass a method from an object, `this` refers to the global object. – JJJ Mar 31 '18 at 22:24
  • Arrow notation does not pass a ‘this’ in the way you’d expect regular function notation to pass it ‘()=>function (){}’ is almost never correct. – Ryan Schaefer Mar 31 '18 at 22:25
  • `person.greet()` has no `return` – charlietfl Mar 31 '18 at 22:30
  • You can do this: `var g = person.greet.bind((() => person)())` but I have no idea why you would want to. It's essentially the same as `person.greet.bind(person)`. It's not really clear what you're trying to accomplish that you can't do just by binding directly to `person` – Mark Mar 31 '18 at 22:37
  • @Mark_M, that's great. can you break this down and explain? With => notation I though we had parameters being passed () and something returned => () You have ...bind( ( () => person) () ) oh, wait, I think I see. Within bind return person immediately () – DCR Mar 31 '18 at 22:45
  • Possible duplicate of [Can you bind arrow functions?](https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions) – Heretic Monkey Mar 31 '18 at 22:46
  • @DCR it's not that great really — it's just an immediately involved function that returns `person` so rather than binding to `person` you're binding to the result of this function…which is `person`. It's extra code that doesn't really do anything. – Mark Mar 31 '18 at 22:47
  • Thanks, I get that. Just trying to better understand what's going on under the hood – DCR Mar 31 '18 at 22:50

0 Answers0