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 {
开发者_StackOverflow中文版 // 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.
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];
}
}
//...
}
Then you can pass an object to init
:
anchorChange4.init({
colors: ['#FFF', '#000']
});
You can do this simply by doing the following in your return object:-
return {
Init: function(params) { init(params); },
Start: start,
Stop: stop,
Pause: pause
}
Did something similar for a plugin i am working on, with a slightly different way and checking passed arguments for objects:
(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
});
}());
精彩评论