module.exports没有返回nodejs中的函数



每个人我都是NODE.JS的初学者,我正在使用module.exports函数,我在里面写了hello函数。我试图从其他文件导入。但它不起作用。有人能解决这个问题吗。提前感谢。。。

index.js
module.exports=function(){   

hello:(data)=>{
return "Good night" +data;
}
}
trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));

当您使用函数作为构造函数,从中创建new对象时,您必须使用this引用这些对象中的每一个来分配它们的属性:

module.exports=function(){
this.hello = (data) => {
return "Good night" +data;
};
}

语法<identifier>:根据其位置/环境而具有不同的含义。当在函数体中使用时,在语句的开头,它只定义一个标签。要让它定义一个属性,必须在对象初始值设定项中使用它。

我发现了一个解决方案,我们必须稍微更改index.js中的代码。在ES6中,函数构造函数是可用的。我们应该使用这个关键字,这个关键字指的是当前类对象。因为在javascript中,函数是第一类对象。如果我错了,请更正我。如果有人知道其他解决方案,请发布答案。。。。

Index.js
module.exports=function(){   
this.hello=(data)=>{
return "Good night" +data;
}
}
Trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));

您也可以这样使用它:

module.exports=function(data){   
return "Good night" +data;
}
const temp = require('./index');
console.log(temp('demo developer'));

我不知道你想找出什么是正确的设计,但你可能想走这条路:

index.js:

exports.hello = data => {
return 'Good night ' + data;
};

trail.js:

const e = require('./index');
console.log(e.hello('Jhonny'));

最新更新