如何将参数传递给模块模式以覆盖JavaScript中的默认值[private properties]?

时间:2011-06-28 09:59:57

标签: javascript

我正在阅读这篇文章http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing,并想知道我是否可以传递参数来覆盖私有属性。

// revealing module pattern
var anchorChange4 = function () {

    // this will be a private property
    var config = {
        colors: [ "#F63", "#CC0", "#CFF" ]
    }

    // this will be a public method
    var init = function () {
        var self = this; // assign reference to current object to "self"

        // get all links on the page
        var anchors = document.getElementsByTagName("a");
        var size = anchors.length;

        for (var i = 0; i < size; i++) {
            anchors[i].color = config.colors[i];

            anchors[i].onclick = function () {
                self.changeColor(this, this.color); // this is bound to the anchor object
                return false;
            };
        }
    }

    // this will be a public method
    var changeColor = function (linkObj, newColor) {
        linkObj.style.backgroundColor = newColor;
    }

    return {
        // declare which properties and methods are supposed to be public
        init: init,
        changeColor: changeColor
    }
}();

anchorChange4.init();

我正在尝试更改数组颜色的值,例如将不同的颜色作为参数传递。我希望我有所作为。

3 个答案:

答案 0 :(得分:6)

您可以使init接受配置参数并使用以下参数扩展私有配置:

var init = function (options) {
    // copy properties of `options` to `config`. Will overwrite existing ones.
    for(var prop in options) {
        if(options.hasOwnProperty(prop)){
            config[prop] = options[prop];
        }
    }
    //...
}

然后您可以将对象传递给init

anchorChange4.init({
    colors: ['#FFF', '#000']
});

答案 1 :(得分:2)

您只需在退货对象中执行以下操作即可: -

return {
        Init: function(params) { init(params); },
        Start: start,
        Stop: stop,
        Pause: pause
    }

答案 2 :(得分:1)

为我正在处理的插件做了类似的事情,方式略有不同,并检查对象的传递参数:

(function() {

    'use strict';


    var MyPlugin = function(){

        var options = null;

        var defaults = {
          className: 'fade-and-drop',
          closeButton: true
        }


        var init = function() {

            // First Extend Default Options
            if (arguments[0] && typeof arguments[0] === "object") {
                options = _extendDefaults(defaults, arguments[0]);
            }

            _somePrivate();
        }

        var _somePrivate = function(){
           //access option as option.parameter
        }

        // Extend defaults with user options
         var _extendDefaults = function(source, properties) {
            var property;
            for (property in properties) {
              if (properties.hasOwnProperty(property)) {
                source[property] = properties[property];
              }
            }
            return source; // to set options var
          }


        return {
            init:init,
        }

    }();

    MyPlugin.init({
        selector:'input__field--select',
        maxWidth: 750
    });

}());