快速简单的方法是这样的:
var PictureDialog = function (settings)
{
settings = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1,
init: function()
{
//Do work
//Show dialog
return this;//<--return object, too
}
};
return settings;//return the object
};
foo = PictureDialog().init();//the init will be called on the return value of PictureDialog
但是,我不明白为什么PictureDialog
函数需要一个settings
参数。要么根本不向函数传递任何内容,要么更改传递的值:
var PictureDialog = (function()
{
var defaults = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1,
init: function()
{
//Do work
//Show dialog
return this;//<--Very important
};
return function (settings)
{
settings = settings instanceof Object ? settings : {};
for (var n in defaults)
{
if (defaults.hasOwnProperty(n))
{//set all properties that are missing from argument-object
settings[n] = settings[n] || defaults[n];
}
}
return settings;
};
}());
foo = PictureDialog({allowShortKey: false}).init();//will return full settings object