简体   繁体   中英

how to call a javascript class function from a another file in node js?

I wanted to call and use class 1 getDescription function to class2. I tried using require and calling the function but can get it. Thanks. I wanted to reuse the function from class1

Class 1

exports.Class1 = class Class1 {
  constructor(options) {
    this.options = options || {};
    this.utils = options.utils;
  }

  getDescription(request) {
    if (request.description) {
      return request.description;
    }

    if (!request.respondent) {
      return 'No description';
    }

    if (request.respondent.employee) {
      return request.respondent.employee.name;
    }

    return `${request.respondent.firstName} ${request.respondent.lastName}`;
  }


};

class2

const Class1  = require('../Class1');

exports.Class2 = class Class2 {
  constructor(options) {
    this.options = options || {};
    this.utils = options.utils;
  }
  const description = Class1.getDescription()
.....

Are you forgetting about the parameter of the getDescription(request) function?

You might also want to instantiate the class, ie let myClass1Obj = new Class1(...) then call myClass1Obj.getDescription(request)

Also, it should be const Class1 = require('../Class1').Class1; in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM