0

I need to bind this keyword inside object using arrow function. Is it possible?

Please don't mark this as duplicate because I have read 10 articles about this here in stackoverflow and I haven't found answer yet. I'm just curious if this is possible because everywhere is just workaround without using arrow function.

This is what I have tried without success.

const person1 = {
  name: 'Dude',
  showName: function(){
    console.log(this.name)
  }
}

const person2 = {
  name: 'Dude',
  showName(){
    console.log(this.name)
  }
}

const person3 = {
  name: 'Dude',
  showName: () => {
    console.log(this.name)
  }
}

const person4 = {
  name: 'Dude',
  showName: (() => {
    console.log(this.name)
  }).bind(this)
}

/* const person5 = {
  name: 'Dude',
  showName: () => {
    console.log(this.name)
  }.bind(this)
} */

person1.showName() // Dude
person2.showName() // Dude
person3.showName() // result
person4.showName() // result
// person5.showName() // SyntaxError
Keri Marr
  • 407
  • 2
  • 6
  • 13
  • 3
    create a class. theres no way to override what's `this` in arrow functions. – Daniel A. White Mar 07 '19 at 17:39
  • 3
    just use a normal function. stop creating problems that don't need to exist – Taplar Mar 07 '19 at 17:40
  • 2
    arrow functions are not mandatory in ES6 – adiga Mar 07 '19 at 17:41
  • Ok, thanks. I was just curious if it is posibble, if I'm missing anything. – Keri Marr Mar 07 '19 at 17:41
  • I'm sure this has been covered before. Did you not find an answer or just not find an answer that you liked? – John Coleman Mar 07 '19 at 17:42
  • 3
    Possible duplicate of [Can you bind arrow functions?](https://stackoverflow.com/questions/33308121/can-you-bind-arrow-functions) and [JavaScript binding - arrow functions and bind](https://stackoverflow.com/questions/50630044) and [Arrow functions using call, apply, bind - not working?](https://stackoverflow.com/questions/43576089) – adiga Mar 07 '19 at 17:44
  • @adiga That is a better duplicate target than the one I picked. In either case, it is a clear duplicate. – John Coleman Mar 07 '19 at 17:45
  • 5
    To further try to explain the potential fustration with this question. Imagine you have a box. It's green. It's existed for a long time. Then someone makes a new box, and it's yellow! And you say, hey, that's pretty cool, I want to use that box..... but I want it to be green. There is a very simple solution to that "issue". – Taplar Mar 07 '19 at 17:46
  • @Taplar A better analogy might be if the yellow box had some very cool features which were seemingly independent of the color but which the green box lacked. – John Coleman Mar 07 '19 at 17:51
  • It's not a perfect analogy, but I think it makes the point, :) – Taplar Mar 07 '19 at 17:52
  • @Taplar No analogy is perfect, and I agree that yours effectively makes an important point. – John Coleman Mar 07 '19 at 17:53

0 Answers0