Joe Slater
Joe Slater

Reputation: 2473

Named arguments in JavaScript

Say I have a function like this

function myFunc(a, b, c)
{
    if(a!=undefined) this.a = a;
    if(b!=undefined) this.b = b;
    if(c!=undefined) this.c = c;
}

And I want to set only the value for b, then I could do something like this.

myFunc(undefined, "some Value for b", undefined);

But I was wondering if there was a way in which I could do something like this for setting the value of b

myFunc(b:"some value for b");

This is probably wrong, but you probably see what I mean. I want to specify the name of the property along with the value so that I do not have to worry about passing undefined values. How would I do this?

Also feel free to change the title, I have no idea what this question should be called.

Upvotes: 1

Views: 640

Answers (3)

OJay
OJay

Reputation: 4921

yes, pass in an object literal

function myFunc(options)
{
    if(options.a!=undefined) this.a = options.a;
    if(options.b!=undefined) this.b = options.b;
    if(options.c!=undefined) this.c = options.c;
}

and call like this

var var1 = new myFunc({b:"some value for b"});

or for a more dynamic, extensible way ( as mentioned)

function myFunc(obj)
{
    for (var i in obj)
    {
        if(obj.hasOwnProperty(i))
        {
            this[i]=obj[i];
        }
    }
}

var func = new myFunc({b:"some value for b"});
console.log(func.b);//"some value for b"

Upvotes: 1

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

Sure, just use this:

function myFunc(options)
{
 if(typeof(options['a']) != "undefined") this.a = options['a'];
 if(typeof(options['b']) != "undefined") this.b = options['b'];
 if(typeof(options['c']) != "undefined") this.c = options['c'];
}

and then call it with

var func = new myFunc({b:"some value for b"});
console.log(func.b);//"some value for b"

Upvotes: 4

jahroy
jahroy

Reputation: 22692

You can achieve this by passing an Ojbect as an argument:

var someObject = { a: 'some A value', b: 'some B value' };

myFunc(someObject);

This is a very common practice.

For example, jQuery uses this construct often.

If you look at the documentation for jQuery.animate(), you can see it accepts a Plain Object as the first argument.

Upvotes: 1

Related Questions