9

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?

Community
  • 1
  • 1
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158

4 Answers4

8

Javascript Module Pattern and yes it attempts to mimic OO Programming with encapsulation

Joe
  • 80,724
  • 18
  • 127
  • 145
0

Thats OOP in JS. Its standard practice.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

This is called the self-invoking (anonymous) function. component returns an object that has an init method, so you can chain the calls together.

dev.bv
  • 980
  • 9
  • 16
jxpx777
  • 3,632
  • 4
  • 27
  • 43
0

You can read about the Module Pattern at the YUI Blog.

Dennis
  • 32,200
  • 11
  • 64
  • 79