How can I take this inline function and convert it to a method while retaining access to this?

I have a JavaScript class that has this kind of structure:

class MyClass () {
    myMethod() {
        myCallback = (response) => {
            // Do a bunch of stuff by referencing and altering properties in this
        }
        apiFunction(this.CLASS_PROP, myCallback);
    }
}

myMethod is already pretty long, and the contents of myCallback make it even longer, so I tried converting it to this structure:

class MyClass () {
    myMethod() {
        apiFunction(this.CLASS_PROP, this.myCallback);
    }
    myCallback = (response) => {
        // Do a bunch of stuff by referencing and altering properties in this
    }
}

Whereas the first version works fine, the second one loses its reference to the MyClass instance and instead this is pointing to, I think, the call is the API that actually called it. I’m not positive as to why, but my theory is that “lexical context” doesn’t mean where the function is defined, but where it’s called.

But my question is, is there a way to break that function out of being inside of myMethod into an instance method of MyClass?

Answer

There are many ways to write that, one of them being

class MyClass  {
    myMethod() {
        apiFunction(this.CLASS_PROP, r => this._myCallback(r));
    }

    _myCallback(response) {
        // Do a bunch of stuff by referencing and altering properties in this
    }
}

Note that in apiFunction there’s an arrow function and _myCallback is an ordinary method (=not arrow). The other way around, like in your code, it won’t work.

The underscore in _myCallback indicates a private method (a convention, not a special syntax).