6

i have this object literal

let p = {
    name : 'Amir',
    say: () => {
        console.log(this.name)
        console.log(this)
    }
}

and I want the say function works using this

p.say();

but the arrow function obviously gets the window object as 'this'. I know I could use a regular function for 'say' instead of arrow and it will work fine.

BUT I would like to ONLY change the call to say function to make it work, but the binding won't work. I mean something like p.say.bind(p)() or p.say.call(p) aint gonna work as desired. Is it possible to change the call to function ONLY and not the say function?

Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33
  • 2
    As the [documentation of arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) explains, they don't have their own `this` and, because of that, they cannot be bound to an object neither using `bind()` nor `call()` or `apply()`. – axiac May 20 '18 at 18:21
  • 4
    The answer is "no". It's not possible by ONLY changing the call site. The reason is that an arrow function simply does not have a `this` binding at all. The `this` you're using is accessed from its outer scope, like any other identifier that your function closes over. It would be like if you defined a `foo` variable outside the function, and then put `console.log(foo)` inside. Because the function doesn't have its own `foo`, it gets the outer one. –  May 20 '18 at 18:22
  • `p.say = p.say.bind(p)` ... – Musa May 20 '18 at 18:23

0 Answers0