Home > Blockchain >  Object destructuring default parameters get all arguments
Object destructuring default parameters get all arguments

Time:02-24

I have a js file with an imported default options and function as below. I am trying to get all the arguments in the function, however it appears that they cannot be used.

import {defaultOptions} from "../defaults.js"

export function getConfig({
  width = defaultOptions.width,
  height = defaultOptions.height,
  fontsize = defaultOptions.fontsize
} = {}) {
   console.log(width); //shows width

   // I want to get all the arguments 
   console.log(arguments); 
}

When I call the function with no parameters like getConfig() and console.log(width) then it shows the width from the defaultOptions from the defaults.js. However the console.log(arguments) returns Arguments object with length 1 where index 0 : undefined.

Is there a way I can get all the arguments in such a function?

Update: See this JSFiddle for something similar where defaults are specified earlier that the function for example. https://jsfiddle.net/coolakul/fa9muzwh/8/

CodePudding user response:

If I am not mistaken, try this :

import { defaultOptions } from "../defaults.js";

export function getConfig(arguments = {}) {
  const { width, height, fontsize } = arguments;
  console.log(width);
  console.log(arguments);
}
getConfig(defaultOptions);

CodePudding user response:

let defaults = {
  width: 300,
  height: 500,
  symbsize: 25,
  margin: {
    top: 10,
    bottom: 10
  }
}

class Config {
    constructor({
      width = defaults.width, 
      height = defaults.height, 
      symbsize = defaults.symbsize, 
      margin = defaults.margin
    } = defaults) {
      this.width = width
      this.height = height
      this.symbsize = symbsize
      this.margin = margin
    }
  
  getConfig() {
    return {
      width: this.width,
      height: this.height,
      symbsize: this.symbsize,
      margin: this.margin
    }
  }
}

const config = new Config({height: 1})

console.log(config.getConfig());

using class should do the work, or i prefer using it

  • Related