/ Published in: JavaScript
The module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.
In JavaScript, the module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of your function names conflicting with other functions defined in additional scripts on the page.
In JavaScript, the module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of your function names conflicting with other functions defined in additional scripts on the page.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var basketModule = (function () { var basket = []; //private function doSomethingPrivate() { //... } function doSomethingElsePrivate() { //... } return { //exposed to public addItem: function (values) { basket.push(values); }, getItemCount: function () { return basket.length; }, doSomething: doSomethingPrivate(), getTotal: function () { var q = this.getItemCount(), p = 0; while (q--) { p += basket[q].price; } return p; } } }()); // basketModule is an object with properties which can also be methods basketModule.addItem({ item: 'bread', price: 0.5 }); basketModule.addItem({ item: 'butter', price: 0.3 }); console.log(basketModule.getItemCount()); console.log(basketModule.getTotal()); // however, the following will not work: console.log(basketModule.basket); // (undefined as not inside the returned object) console.log(basket); //(only exists within the scope of the closure)