Javascript/jQuery: Varying parameters on a custom function
I'm writing a plugin that will allow parameters to 'set it up.' But I predict the user won't always want to set up every aspect of the function.
function This_Function(a,b,c,d);
For instance, maybe they'll only want to set up a
and c
, but not b
and d
(they'll just prefer to leave those as defaults). How do I write the function (or the parameters for that matter) so that the user can customize which functions they would prefer to pass? I have a feeling it involves parsing input, but I've seen many other functions with this capabi开发者_如何学Pythonlity.
Thanks in advance for the help.
function This_Function(options){
// set up the defaults;
var settings = {
'opt1':2,
'opt2': 'foobar'
};
$.extend(settings,options);
if (settings.opt1 > 10) {
//do stuff
}
}
Will let you users do something like this:
This_Function();
This_Function({'opt1':30});
This_Function({'opt2':'jquery'});
This_Function({'opt1':20,'opt2':'javascript'});
A more transparent way...
function This_Function(options) {
var a = options.a;
var b = options.b;
var c = options.c;
var d = options.d;
}
This_Function({a:12; c:'hello'; d:1);
I think the answer I was really looking for for this problem was this one:
function bacon(){
for( var i in arguments ){
if( arguments.hasOwnProperty(i) ){
console.log( arguments[i] );
}
}
}
bacon( 'foo', 'bar', 'baz', 'boz' );
// 'foo'
// 'bar'
// 'baz'
// 'boz'
To make sure the arguments you're utilizing are legitimate parameters being passed to the function, you should check each property with .hasOwnProperty()
.
Only took me 3 years to figure it out :)
精彩评论