Javascript bind prototype instance to its property's function

This question already has an answer here:

  • Organize prototype javascript while perserving object reference and inheritance

    3 answers

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?

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.