Tabachi Harada
Tabachi Harada

Reputation: 65

Cannot access function through this

I was trying to figure out how this works and I tried a few things. But I keep on getting an a TypeError which clearly means that I have not assigned the this variable correctly. Would be great if someone could point out where am I going wrong, and if the way I am using is correct or not.

So,

I have a main file, service.js

class Service {
  constructor() {
    const cronService = new (require('./cron.js'))(this);
    cronService.start();
    this.newService = new (require('./newService.js'))(this);
  }
}

const x = new Service();

This accesses two other files,

newService.js

class NewService {
  constructor(service) {
    this.service = service;
    this.logger = this.service.logger;
    this.system = this.service.system;
  }

  async function1() {
    console.log('woohoo');
  }
}
module.exports = NewService;

and cron.js

class CronService {
  constructor(service) {
    this.service = service;
  }

  async start() {
    await this.f2();
  }

  async f2() {
    const self = this;
    self.service.function1();
  } 
}
module.exports = CronService;

When I run node service.js, I expect a console log of woohoo. But I keep on getting an error, that self.service.function1 is not a function.

I have tried many combinations like self.function1, this.function1, this.service.newService.function1 but all of them either result in the above TypeError or it leading to be undefined.

How to look at this issue? What am I doing wrong? I know I could directly import newService.js but I was looking to learn if I could call function1 from cron.js without importing it into cron.js. Thanks

Upvotes: 1

Views: 67

Answers (1)

Ele
Ele

Reputation: 33736

According to the logic in the code you've posted, probably what you really want is passing this.newService as param in new CronService(this.newService).

class NewService {
  constructor(service) {
    this.service = service;
    this.logger = this.service.logger;
    this.system = this.service.system;
  }

  function1() {
    console.log('woohoo');
  }
}
//module.exports = NewService;

class CronService {
  constructor(service) {
    this.service = service;
  }

  start() {
    this.f2();
  }

  f2() {
    const self = this;
    self.service.function1();
  }
}
//module.exports = CronService;

class Service {
  constructor() {
    this.newService = new NewService(this);
    const cronService = new CronService(this.newService);
    cronService.start();
  }
}

const x = new Service();

Upvotes: 1

Related Questions