Javascript object function with parameters

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

insertButton({ settings:{ value1:'Some text' } }); function insertButton(settings){ settings = new Object(); document.write(settings.value1); } 

Obviously this will not work, but I'm trying to show what I mean. Maybe someone can help.

I ask because now I have a simple function where I can pass values ​​in strict order. With options, I want to be independent of the order of the variables in the function. For instance:

 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 that the "c" value3 is not convenient for me. That is why I would like to try objects, parameters.

thanks.

+4
source share
3 answers

You simply pass functions to the 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 name parameters in js, so {settings:{}} will pass an object with the settings key (so inside functions you will need to do settings.settings )

  • You updated 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, the new Object - iffy - object literal {} is cooler

+7
source

Well, you rewrite settings into an empty object in the first line of your function, take it out and work ...

Edit: Sorry, early removal of the settings object from the arguments should be

 insertButton({ value1:'Some text' }); 
+2
source

try it

 function insertButton(settings){ document.write(settings.value1); } insertButton({ value1:'Some text' }); 
+1
source

Source: https://habr.com/ru/post/1379641/


All Articles