Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 676
devjs11 Avatar asked Dec 16 '22 07:12

devjs11


1 Answers

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

like image 60
Zirak Avatar answered Dec 21 '22 23:12

Zirak