devjs11
devjs11

Reputation: 1948

Javascript object function with options

I am trying to create a function with options. I believe I have to use objects but have failed so far. By options I mean something like that:

insertButton({
    settings:{
        value1:'Some text'      
    }
});

function insertButton(settings){
    settings = new Object();    
    document.write(settings.value1);
}

Obviously, that won't work but I am trying to show what I mean. Maybe someone could help.

I am asking because right now I have simple function where I can pass values with strict order. With options I want to be undependable of variables order in function. For example:

function insertButton2(value1,value2,value3){
    document.write(value1);
    document.write(value2);
    document.write(value3);   
}

insertButton2('a','','c');  //empty commas to skip value2 

Leaving empty commas to make sure 'c' is value3 is not convenient for me. That is why I would like to try objects, options.

Upvotes: 4

Views: 13676

Answers (3)

Jan Turoň
Jan Turoň

Reputation: 32912

Try this

function insertButton(settings){
    document.write(settings.value1);
}

insertButton({
    value1:'Some text'      
});

Upvotes: 2

JaredMcAteer
JaredMcAteer

Reputation: 22536

Well you're overwriting settings to a blank Object in the first line of your function, take that out and it will work...

Edit: Sorry early remove the settings object from the arguments should just be

insertButton({
       value1:'Some text'      
});

Upvotes: 2

Zirak
Zirak

Reputation: 39808

You just pass into the function an object with the required keys/values:

function parameterify(params) {
    console.log(params.isAwesome);
}

parameterify({
    isAwesome : true
});
//logs true

You had two mistaknes:

  1. There are no names parameters in js, so {settings:{}} would pass an object with a key of settings (so that inside of the functions, you'd have to do settings.settings)

  2. You redeclared settings at the top of the function (settings = new Object();), which no matter what you pass in will always overwrite it. As a side note, new Object is iffy - object literal {} is way cooler

Upvotes: 8

Related Questions