0

I'm grouping some prototype methods into that prototype's property. How can I bind the this reference of those methods to the prototype instance instead of that property.

MyClass.prototype.doSomeThing = function() {
    //this refers to the instance
} 

//after grouped

MyClass.prototype.group = {

   doSomeThing() {
       //this refers to instance.group, which is not what I wanted
   }
}

How can I achieve this? Or is that impossible?

Sean C.
  • 1,494
  • 1
  • 13
  • 22

1 Answers1

0

The value of this is determined by how you call the method. So if you use:

this.group.doSomething(arg1, arg2, arg3)

The context is MyClass.prototype.group. You need to call the method differently:

this.group.doSomething.call(this, arg1, arg2, arg3)

or:

this.group.doSomething.apply(this, [arg1, arg2, arg3])

Alternatively, you could recreate the group object, assign it to the instance, and bind the methods to the instance all from within the constructor. However, this effectively sidesteps the benefits of prototype inheritance. You would be creating a new function instance for every method on every instance of your class.

Perhaps if you gave some context as to why you feel you need to namespace your instance methods (a very uncommon practice, I'd say), someone could suggest a better alternative. I feel like if your objects have so many instance methods that they need to be grouped/namespaced, your class does too much and there is probably a better architectural approach.

sbking
  • 7,630
  • 24
  • 33
  • I'm rewriting some methods of a third-party library. I don't want to overwrite them, neither postfix or prefix them. Looks like I have no other choices but renaming ;( – Sean C. Aug 02 '17 at 16:47
  • @SeanC. Why not subclass the library class? Prototypes are there to allow an object-oriented style of extensibility, after all. It's generally a better practice to subclass than to modify a third party prototype object. – sbking Aug 02 '17 at 16:47
  • It's like a plugin style. The original class is referenced somewhere else which I cannot replace with a subclass – Sean C. Aug 02 '17 at 16:51
  • @SeanC. It's probably better to just make your group methods take an object instance as the first argument (instead of `this`), and then don't store them on the third party prototype. Use them as a library and make them available where needed. No need to co-opt prototype inheritance and make it work differently than it was designed to. – sbking Aug 02 '17 at 16:54
  • OK I get it. But I'd rather postfix them like `doSomeThingEx`. Thanks for the ideas! – Sean C. Aug 02 '17 at 17:00