I'm studying the object oriented features of Javascript and I'm looking at the "Module Pattern". I have a self executing function, which I'd like to call from another file but I keep getting errors.
Here's the self executing module:
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;
},
};
})();
I'm trying to use this from another file called Run.js:
var basketModule = require("./basketModule");
basketModule.addItem({
item: "bread",
price: 0.5
});
console.log( basketModule.getItemCount() );
When I run this node Run.js I get an error:
basketModule.addItem is not a function.
I tried adding a call to basketModule like this: basketModule(); immediately after the require but this results in
TypeError: basketModule is not a function.
What am I missing?
console.log( basketModule.getItemCount());
You need to module export the class before you can use it by calling require, add module.exports = basketModule; after the function.
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;
Also in your other file
var basketModule = require("./src/basketModule.js");
basketModule.addItem({
item: "bread",
price: 0.5
});
console.log(basketModule.getItemCount());
In the above I have created a new instance of our basketModule and then called .addItem()on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With