Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The reference to the class in ES6 is lost [duplicate]

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() 
like image 660
Alan Olivares Avatar asked Sep 18 '25 14:09

Alan Olivares


1 Answers

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)
like image 54
Alexander O'Mara Avatar answered Sep 20 '25 03:09

Alexander O'Mara