Search code examples
javascriptnode.jsclassecmascript-6eventemitter

NodeJs/Javascript access parent method in nested class


class Foo extends EventEmitter {
    constructor(name) {
        this.name = name;
    }
    funcA(sourceRepositoryPath, branch) {

        this.emit('log', 'Hello from Foo');

        var bar = new Bar();
        bar.on('log', function(log) {
            this.emits('log', 'Hello from Foo from Bar');
        });
    }
}

How can i use the emit function from Foo inside the bar.on... function like the

this.emit('log', 'Hello from Foo');

function in ES6?

var foo = new Foo();
foo.funcA();

foo.on('log', function(log) {
    // expects : Hello from Foo && Hello from Foo from Bar 
    // gets : Hello From Foo   
});

Solution

  • The arrow function syntax solves this exact problem:

    class Foo extends EventEmitter {
        constructor(name) {
            this.name = name;
        }
    
        funcA(sourceRepositoryPath, branch) {
            this.emit('log', 'Hello from Foo');
    
            var bar = new Bar();
            bar.on('log', (log) => {
                this.emits('log', 'Hello from Foo from Bar');
            });
        }
    }
    

    Other than a shorter, more concise syntax, arrow functions define a "lexical this", meaning the this keyword inside an arrow function resolves to the instance where the function is defined.