简体   繁体   English

如何从module.exports访问函数

[英]How to access function from module.exports

I have the following code in test1.js . 我在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 . 我正在尝试访问test2.js上的功能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. 谢谢。

It is very unclear what you're trying to achieve here. 目前尚不清楚您要在这里实现什么。

You're exporting a function . 您正在导出一个函数 That function will take 1 argument ( d ). 该函数将带有1个参数( d )。 Then you try to assign the demo1 and demo2 properties, of that received argument, to two different functions. 然后尝试分配demo1demo2特性,接受的说法,两个不同的功能。

What I think you want to do is that you want to export an object with two different properties for those functions. 您想要做的是要导出一个具有两个不同属性的对象,这些功能。 Eg 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: 然后你就可以导入模块并访问demo1demo2功能:

var demo = require('./test1');
var result = demo.demo1();
var demo = require('./test1');
var o = {};
demo(o);
o.demo1(); // "DEMO 1";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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