javascriptecmascript-6class-reference

The reference to the class in ES6 is lost


I have the following structure Javacript es5-es6 and the controller class loses the reference in the class Get, I was already investigating but I can not find how to avoid losing the reference.

class Controller {
    constructor() {
        this.name = 'Test';
    }
    test() {
        console.log(1, this.name);
    }
}

referenceController = new Controller();
// working reference: console.log(1, 'Test');
referenceController.test();


class Get {
    method() {
        return {
            controller: referenceController.test
        }
    }
}

// Lost self reference: console.log(1, undefined)
new Get().method().controller() 

Solution

  • In this section, you add the test function as a property of the returned object.

    {
        controller: referenceController.test
    }
    

    Then, when you call it as a method of that object (method().controller()) this refers to the object, and the name property is read from the object.

    You could bind the context to preserve the reference:

    referenceController.test.bind(referenceController)