Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Calling functions of a class via apply doesn't initialize the values in the constructor

I have javascript classes in multiple files. I would like to call a function from a given class by only supplying their names as arguments.

class Index{
    constructor(){
        this.Loader("test", "TestFunc");
    }

    Loader(cname, fname){
        const template = require(`./${cname}.js`);
        const object = new template();
        object[fname].apply();
    }
}

new Index();
module.exports = class Test{
    constructor(){
        this.text = "this text should appear";
    }

    TestFunc(){
        console.log(this.text);
    }
}

When the instance of the Test class gets initialized the constructor will run and prepare the value, but when I call TestFunc via the apply function the same values appear undefined and the error "Cannot read property text of undefined" gets thrown. When calling the function normally via object.TestFunc(); no such error is present.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!