0

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 capability.

Thanks in advance for the help.

3 Answers 3

7
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'});
Sign up to request clarification or add additional context in comments.

3 Comments

If you're using JQuery, this is the way to do it.
Figured if they added the jQuery tag they were using jQuery
This is exactly what I was looking for. You're a saint, Plynx.
1

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

1 Comment

This is great, too. Thanks. I gave you +1.
0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.