如何将参数传递给模块模式以覆盖JavaScript中的默认值[private properties]? [英] How can I pass parameters to a module pattern to override default values [private properties] in JavaScript?

查看:48
本文介绍了如何将参数传递给模块模式以覆盖JavaScript中的默认值[private properties]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was reading this article http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing and was wondering if I can pass parameters to override the private properties.

// 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();

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

I'm trying to change the values of the Array colors, like passing different colors as parameters. I hope I'm making some sense.

推荐答案

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

You can make init accept a configuration parameter and extend the private configuration with this one:

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

Then you can pass an object to init:

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

这篇关于如何将参数传递给模块模式以覆盖JavaScript中的默认值[private properties]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆