开发者

What is this pattern called in Javascript? does it have a name?

开发者 https://www.devze.com 2023-03-31 19:05 出处:网络
component.js var component = (function(){ var self; var default_options = { array_option : [], string_option : \"default\"

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?


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


Thats OOP in JS. Its standard practice.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消