0

I have this class:

class A {
  name = 'foo';

  displayName() {
    console.log(this.name);
  }
}

And I'd like to call the displayName method within a callback after the instantiation. I've done this:

const a = new A();
someCode('blabla', a.displayName.bind(a));

But I don't like this. Is there a more elegant way to do it?

Kerumen
  • 3,401
  • 1
  • 16
  • 31
  • Are you talking about the `bind` as not being elegant? – nils Nov 25 '16 at 15:24
  • The class syntax you are using is not valid ES6. But if you are using experimental syntax anyway, you might want to have a look at [this](http://stackoverflow.com/q/35495919/1048572) – Bergi Nov 25 '16 at 15:24
  • `const A = new A();` will always throw an exception. I assume you meant `const a = new A();`? – Bergi Nov 25 '16 at 15:25
  • @nils the `bind(a)` – Kerumen Nov 25 '16 at 15:32
  • @Bergi Yes I edited. – Kerumen Nov 25 '16 at 15:33
  • @Bergi I already read this answer but didn't find something that suits my needs... – Kerumen Nov 25 '16 at 15:34
  • @Kerumen the question Bergi is linking to answers you question precisely. – nils Nov 25 '16 at 15:36
  • @nils It's all about binding `this`. Nevermind I guess this is the only way to do this. – Kerumen Nov 25 '16 at 15:42
  • Maybe I misunderstand your point then. Is it not about binding this? – nils Nov 25 '16 at 15:44
  • It is. But not _inside_ the class. – Kerumen Nov 25 '16 at 15:45
  • @Kerumen If you don't want to bind it inside the class (which would make the callback passing most elegant: `someCode('blabla', a.displayName)`) in any way, you have to [bind it outside](http://stackoverflow.com/q/20279484/1048572). If you don't like `bind`, function expressions or arrow functions are basically your only alternative. – Bergi Nov 25 '16 at 15:50
  • @Bergi How can I bind it inside the class? I'm interested! – Kerumen Nov 25 '16 at 15:52
  • @Kerumen Or maybe if you're into [experimental syntax](http://stackoverflow.com/a/31221199/1048572), you might use `someCode('blabla', ::a.displayName)`. But really you have to tell us *what* you don't like about `someCode('blabla', a.displayName.bind(a));` to get a useful answer. – Bergi Nov 25 '16 at 15:52
  • @Kerumen Oops, I thought I used that link as the dupe target already. If you want to bind inside the class, your question is essentially an exact duplicate of [this](http://stackoverflow.com/q/35495919/1048572) – Bergi Nov 25 '16 at 15:55
  • @Bergi Ok I ended up using the (experimental) arrow function syntax so I don't have to bind it in the callback. Thanks! – Kerumen Nov 25 '16 at 16:08
  • It's not the arrow functions that are experimental, it's the assignment statement outside of the constructor (like you did with `name = 'foo'`) – Bergi Nov 26 '16 at 14:02

0 Answers0