Search code examples
javascriptnode.jsecmascript-5ecma

Use .call when I instantiate a new class


I try to call a function of classA inside my mainClass. And then I try to call functions of mainClass inside classA. I tried to use .bind() and .call() but it doesn't work. It only works if I use .bind(this) or .call(this) on functions, but not while I try to instantiate a new class.

index.js

let ClassA = require('./ClassA')

class mainClass {

    constructor() {
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA().call(this)
        classA.doSomething()
    }

    aFunction() {
        console.log('done')
    }

}

new mainClass()

classA.js

module.exports = class ClassA {

    constructor() {
    }

    doSomething() {
        console.log('doSomething')
        this.doSomething2()
    }

    doSomething2() {
        this.aFunction() // main Class
    }

}

TypeErrpr: this.doSomething2 is not a function


Solution

  • In a comment you've clarified what you're trying to do (it's also a code comment in the question):

    How can I call aFunction() from classA then?

    You'd do that by giving the code in ClassA access to your instance. You might pass it to the constructor which could save it as an instance property, or you might pass it to doSomething.

    Here's an example passing it to the constructor:

    class ClassA {
    
        constructor(obj) {           // ***
            this.obj = obj;          // ***
        }
    
        doSomething() {
            console.log('doSomething');
            this.doSomething2();
        }
    
        doSomething2() {
            this.obj.aFunction();    // ***
        }
    
    }
    
    class mainClass {
    
        constructor() {
            this.doSomething();
        }
    
        doSomething() {
            let classA = new ClassA(this);
            classA.doSomething();
        }
    
        aFunction() {
            console.log('done');
        }
    }
    
    new mainClass();