component.js
var component = (function(){
var self;
var default_options = {
array_option : [],
string_option : "default"
};
return {
other_function: function(args) {
},
init: function(options) {
self = this;
// merge in user options
for (var attr in options) {
if (options.hasOwnProperty(attr)) {
self.o[attr] = options[attr];
}
}
/***
* Initialize component
*/
self.other_function(args);
}
};
})();
then in the html
<script src="component.js"></script>
<script>
// init the component
component.init({
array_option : [1,2,3],
});
</script>
The reason I ask is I have seen it by example and thought it made sense, but is their any reading on why this is good practice? is this Object-Oriented Javascript?
if this IS OO javascript, does this pattern make prototypal definitions useless?
Good answer to above question
Javascript: Module Pattern vs Constructor/Prototype pattern?
A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.
JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code. For those that are familiar with object-oriented languages, modules are JavaScript “classes”.
Each pattern has a name and becomes part of a vocabulary when discussing complex design solutions. The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral (see below for a complete list).
Javascript Module Pattern and yes it attempts to mimic OO Programming with encapsulation
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