[英]How can I export module pattern function to another JavaScript file
I have two JavaScript files and would like to export the file with module pattern to another file.我有两个 JavaScript 文件,想将具有模块模式的文件导出到另一个文件。 The file with module pattern, I would like to export only public members.带有模块模式的文件,我只想导出公共成员。 When I try to execute the test, it says that "Calculator is not a constructor".当我尝试执行测试时,它说“计算器不是构造函数”。
file: calculator.js文件:calculator.js
var Calculator = function(){
var total = null;
return {
add: function(x,y){
total = x + y;
},
getTotal: function(){
return total;
};
display: function(){
console.log(total);
}
}
}
second file: testCalculator.js第二个文件:testCalculator.js
const calculatorObj = require('calculator.js');
describe("Calculator test suite", function(){
var calculatorObj = new Calculator();
it('Verify sum method', function() {
try{
calculatorObj.add(5,5);
//assertive
expect(10, calculatorObj.getTotal());
}
catch(err)
{
alert(err);
}
});
});
It is not working, because you need to export something before consuming it.它不起作用,因为您需要在使用之前导出一些东西。
Add this code to make it work添加此代码以使其工作
module.exports = function(){
var total = null;
return {
add: function(x,y){
total = x + y;
},
getTotal: function(){
return total;
};
display: function(){
console.log(total);
}
}
}
do I have to list all the function names that I want to export?我必须列出所有要导出的 function 名称吗?
Yes, you have to export all things you want to import later.是的,你必须导出所有你想稍后导入的东西。 Or you can export one single object with all code you need.或者您可以导出一个 object 以及您需要的所有代码。
do i need to use "import" or "require()"我需要使用“import”还是“require()”
For Node.js, require
is common practice.对于 Node.js, require
是常见的做法。 Latest Node.JS supports import
construction, but, at least for now, using require is preferable.最新的 Node.JS 支持import
构造,但至少目前,使用 require 更可取。
For browsers, you will use import
notation.对于浏览器,您将使用import
符号。
And your function is not a classical constructor, please, take a look into the class notation而您的 function 不是经典构造函数,请查看class符号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.