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.
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:
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
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With