最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access function from module.exports - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Apr 12, 2016 at 9:02 Daniel Higueras 2,40423 silver badges35 bronze badges asked Apr 1, 2016 at 8:38 Raju KumarRaju Kumar 231 silver badge3 bronze badges 1
  • Possible duplicate of Can we call the function written in one JavaScript in another JS file? – Pugazh Commented Apr 1, 2016 at 9:35
Add a ment  | 

2 Answers 2

Reset to default 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();
var demo = require('./test1');
var o = {};
demo(o);
o.demo1(); // "DEMO 1";
发布评论

评论列表(0)

  1. 暂无评论