Last active
August 29, 2015 14:10
-
-
Save botmaster/eaf351d824a7db488020 to your computer and use it in GitHub Desktop.
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript The module itself is completely self-contained in a global variable called basketModule. The basket array in the module is kept private and so other parts of our application are unable to directly read it. It only exists with the module's closure and…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var basketModule = (function () { | |
// privates | |
var basket = []; | |
function doSomethingPrivate() { | |
//... | |
} | |
function doSomethingElsePrivate() { | |
//... | |
} | |
// 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; | |
}, | |
// Public alias to a private function | |
doSomething: doSomethingPrivate, | |
// Get the total value of items in the basket | |
getTotal: function () { | |
var q = this.getItemCount(), | |
p = 0; | |
while (q--) { | |
p += basket[q].price; | |
} | |
return p; | |
} | |
}; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// basketModule returns an object with a public API we can use | |
basketModule.addItem({ | |
item: "bread", | |
price: 0.5 | |
}); | |
basketModule.addItem({ | |
item: "butter", | |
price: 0.3 | |
}); | |
// Outputs: 2 | |
console.log( basketModule.getItemCount() ); | |
// Outputs: 0.8 | |
console.log( basketModule.getTotal() ); | |
// However, the following will not work: | |
// Outputs: undefined | |
// This is because the basket itself is not exposed as a part of our | |
// the public API | |
console.log( basketModule.basket ); | |
// This also won't work as it only exists within the scope of our | |
// basketModule closure, but not the returned public object | |
console.log( basket ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment