0

I have an object created with a constructor:

var mngr = new Manager();

It has a property contacts and a method showContacts() { return this.contacts }.

I also have another object, say, named company which runs some actions then in the end it needs to make mngr object run its showContacts()

I declare company and add a method from mngr to it:

var company = new Company({
    onFinish: mngr.showContacts
});

Now when I run the code from company object, it executes the function onFinish which is borrowed from mngr.showContacts, so it runs in context of the company, not mngr.

How do I make it perform the method on the mngr?

I have these variants:

var company = new Company({
    onFinish: mngr.showContacts.bind(mngr)
});

and:

var company = new Company({
    onFinish: function(){mngr.showContacts()}
});

Both seems not perfect.

How should I do it the right way?

Sergei Basharov
  • 43,294
  • 56
  • 177
  • 295
  • 1
    How are they "not perfect" ? What do you want better ? BTW there's no such thing as an "original containing object", there's no link from a value to its assignements. – Denys Séguret Dec 24 '15 at 14:03
  • Well, if these are a normal way, then I am fine with it. Just seems like there must be a more beautiful way than these, but if not, then that's ok. – Sergei Basharov Dec 24 '15 at 14:05
  • The thing is a value has no owner. There was a proposal in ES? to make it easier to write `mngr.showContacts.bind(mngr)` (something like `::mngr.showContacts` I think) but that's about all and it doesn't seem to be on its way. – Denys Séguret Dec 24 '15 at 14:06
  • 1
    ES7 proposes a [double colon syntax](http://stackoverflow.com/q/31220078/1529630). – Oriol Dec 24 '15 at 14:06
  • @Oriol I think it's about dead, no ? – Denys Séguret Dec 24 '15 at 14:07
  • Ok, then which one of these two I proposed is preferred and why? – Sergei Basharov Dec 24 '15 at 14:08
  • @SergeiBasharov: Both are totally fine. Arrow functions or binding the method on creating might *look* better if your care about that. – Bergi Dec 24 '15 at 14:09
  • @DenysSéguret: No, why do you think so? – Bergi Dec 24 '15 at 14:09
  • @Bergi It looked dead. I'm glad to hear it's on its way (I can't follow the ES discussion like you do, so I just trust you on that). Thanks. – Denys Séguret Dec 24 '15 at 14:11

0 Answers0