我正在研究 Javascript 的面向对象特性,并且正在研究“模块模式”。我有一个自执行函数,我想从另一个文件调用它,但我不断收到错误。
这是自执行模块:
var basketModule = (function () {
var basket = [];
function doSomethingPrivate() {
//...
}
// Return an object exposed to the public
return {
// Add items to our basket
addItem: function( values ) {
basket.push(values);
},
// Get the count of items in the basket
getItemCount: function () {
return basket.length;
},
};
})();
我正在尝试从另一个名为 Run.js
的文件中使用它:
var basketModule = require("./basketModule");
basketModule.addItem({
item: "bread",
price: 0.5
});
console.log( basketModule.getItemCount() );
当我运行此 node Run.js
时出现错误:
basketModule.addItem is not a function.
我尝试像这样添加对 basketModule 的调用:basketModule();
紧随 require 之后,但这会导致
TypeError: basketModule is not a function.
我错过了什么?
console.log( basketModule.getItemCount());
最佳答案
调用require使用前需要模块导出类,在函数后添加module.exports = basketModule;
var basketModule = (function () {
var basket = [];
function doSomethingPrivate() {
//...
}
// Return an object exposed to the public
return {
// Add items to our basket
addItem: function( values ) {
basket.push(values);
},
// Get the count of items in the basket
getItemCount: function () {
return basket.length;
},
};
})();
module.exports = basketModule;
也在你的其他文件中
var basketModule = require("./src/basketModule.js");
basketModule.addItem({
item: "bread",
price: 0.5
});
console.log(basketModule.getItemCount());
在上面,我创建了一个新的 basketModule 实例,然后在其上调用了 .addItem()
。
关于javascript - 如何从另一个文件调用自执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163890/