Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Answer

Commonmark migration
Source Link

##Sounds of Future

Sounds of Future

##Sounds of Future

Sounds of Future

added 616 characters in body
Source Link
jave.web
  • 15.3k
  • 15
  • 110
  • 136

EDIT: Due to comments regarding const options - the problem with using constant options in the rest of the function is actually not that you can't do that, is just that you can't use the constant variable in its own declaration - you would have to adjust the input naming to something like

function test(input_options){
 const options = {
 // defaults
 someKey: 'someDefaultValue',
 anotherKey: 'anotherDefaultValue',
 // merge-in input options
 ...input_options
 };
 // from now on use options with no problem
}

EDIT: Due to comments regarding const options - the problem with using constant options in the rest of the function is actually not that you can't do that, is just that you can't use the constant variable in its own declaration - you would have to adjust the input naming to something like

function test(input_options){
 const options = {
 // defaults
 someKey: 'someDefaultValue',
 anotherKey: 'anotherDefaultValue',
 // merge-in input options
 ...input_options
 };
 // from now on use options with no problem
}
Source Link
jave.web
  • 15.3k
  • 15
  • 110
  • 136

##Sounds of Future

In future, you will be able to "spread" one object to another (currently as of 2019 NOT supported by Edge!) - demonstration how to use that for nice default options regardless of order:

function test(options) {
 var options = {
 // defaults
 url: 'defaultURL',
 some: 'somethingDefault',
 // override with input options
 ...options
 };
 
 var body = document.getElementsByTagName('body')[0];
 body.innerHTML += '<br>' + options.url + ' : ' + options.some;
}
test();
test({});
test({url:'myURL'});
test({some:'somethingOfMine'});
test({url:'overrideURL', some:'andSomething'});
test({url:'overrideURL', some:'andSomething', extra:'noProblem'});

MDN reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

...meanwhile what Edge DOES support is Object.assign() (IE does not, but I really hope we can leave IE behind :) )

Similarly you could do

 function test(options) {
 var options = Object.assign({
 // defaults
 url: 'defaultURL',
 some: 'somethingDefault',
 }, options); // override with input options
 
 var body = document.getElementsByTagName('body')[0];
 body.innerHTML += '<br>' + options.url + ' : ' + options.some;
 }
 test();
 test({});
 test({url:'myURL'});
 test({some:'somethingOfMine'});
 test({url:'overrideURL', some:'andSomething'});
 test({url:'overrideURL', some:'andSomething', extra:'noProblem'});

lang-js

AltStyle によって変換されたページ (->オリジナル) /