如何将参数传递到模块模式以覆盖JavaScript中的默认值[private properties]
How can I pass parameters to a module pattern to override default values [private properties] in 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();
我正在尝试更改数组颜色的值,就像传递不同的颜色作为参数一样。我希望我说得有道理。
您可以让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']
});
您只需在返回对象中执行以下操作即可完成此操作:-
return {
Init: function(params) { init(params); },
Start: start,
Stop: stop,
Pause: pause
}
为我正在开发的插件做了类似的事情,但方式略有不同,并检查对象的传递参数:
(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
});
}());
相关文章:
- 我的shareService在angular 2中发送值工作正常,但当我渲染我的另一个组件时,会获得默认值
- jquerydatetimepicker日期和时间应在框默认值中,而无需单击框
- 如果值为空,如何设置输入的默认值?jQuery
- 骨干模型默认值-todos.js示例中不必要的代码
- jquery日期选择器年份范围默认值
- Html5输入属性的默认值,如最小值、最大值、大小等
- 根据两个下拉列表的默认值禁用按钮
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- Angularjs-设置不带ng选项的select的默认值
- jQuery Datepicker从日期开始设置默认值
- 如何设置浏览器打开的文件对话框的文件名(一些默认值)
- JQuery BlockUI鼠标加载光标没有't在Google Chrome中返回默认值
- Selectize选择默认值
- 在KeystoneJS中为Types.Money设置默认值
- 是否可以同时为一个元素的所有事件指定阻止默认值
- 防止在IE7中按回车键时出现默认值
- 如何覆盖jqGrid's语言默认值
- 如何为显示jquery滑块值的文本框设置默认值
- 当数组在angularjs中没有可比较的值时,如何分配默认值
- 如何将参数传递到模块模式以覆盖JavaScript中的默认值[private properties]