1

I have the following code in test1.js.

module.exports = function(d){
  d.demo1 = function() {
    return "DEMO 1";
  },

  d.demo2 = function() {
    return "DEMO 2";
  }
}

I am trying to access function demo1 on test2.js. Below the code which call the function.

var demo = require('./test1');
var result = demo.****;        //code to call function demo1
console.log("calling function", result); //output should be "calling function DEMO 1"

Please help how can I access this function. Thanks.

Daniel Higueras
  • 2,404
  • 22
  • 34
Raju Kumar
  • 23
  • 1
  • 3
  • Possible duplicate of [Can we call the function written in one JavaScript in another JS file?](http://stackoverflow.com/questions/3809862/can-we-call-the-function-written-in-one-javascript-in-another-js-file) – Pugazh Apr 01 '16 at 09:35

2 Answers2

7

It is very unclear what you're trying to achieve here.

You're exporting a function. That function will take 1 argument (d). Then you try to assign the demo1 and demo2 properties, of that received argument, to two different functions.

What I think you want to do is that you want to export an object with two different properties for those functions. E.g. doing this:

module.exports = {
  demo1: function() {
    return "DEMO 1";
  },

  demo2: function() {
    return "DEMO 2";
  }
}

Then you can import the module and access the demo1 and demo2 functions as:

var demo = require('./test1');
var result = demo.demo1();
Emil Oberg
  • 4,006
  • 18
  • 30
1
var demo = require('./test1');
var o = {};
demo(o);
o.demo1(); // "DEMO 1";
Vladimir G.
  • 885
  • 7
  • 15