1

I'm trying to separate the concerns in my code. I want to build a config file where i use the same method to set something. Please note that this is just for demo purpose. Is there a way that I could call the function based on either car or bike of the config object selected. If so, could you please guide me?

I was getting setYear is undefined error. I want to set the year of car object from the config object. I want to access the setYear function using the config object.

const buildConfig = () => {
  const car = {}
  car.label = config['car'].label;
  car.year = config['car'].setYear('2020')
  console.log('car details', car);
}

const config = {
  'car': {
    label: 'Sedan',
    setYear: setYear
  },
  'bike': {
    label: 'Sedan',
    setYear: setYear
  }
}

const setYear = (year) => {
  car.year = year;
}

buildConfig();
scriobh
  • 868
  • 10
  • 25
  • Neither car nor bike has a year property? – Jonas Wilms Jun 19 '20 at 05:19
  • @JonasWilms I'm constructing the object by setting the values. So, the car need not have any predefined keys. – scriobh Jun 19 '20 at 05:21
  • 1
    Hope this will help you understand how to solve your issue. [Can you bind `this` in an arrow function?](https://stackoverflow.com/questions/33308121/can-you-bind-this-in-an-arrow-function) – Karan Jun 19 '20 at 05:29
  • See also [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/q/34361379/218196) – Felix Kling Jun 19 '20 at 07:34

1 Answers1

3

Please use setYear as normal function and use this to access object property

To know why this works with function check this Can you bind this in an arrow function?

const buildConfig = () => {
  const car = {}
  car.label = config['car'].label;
  car.year = config['car'].setYear('2020')
  console.log('car details', car);
}

const setYear = function(year) { // Use normal function
  this.year = year; // Use this to assign year
  return this.year; // Return assigned year 
}

const config = {
  'car': {
    label: 'Sedan',
    setYear: setYear
  },
  'bike': {
    label: 'Sedan',
    setYear: setYear
  }
}

buildConfig();
Jay
  • 2,826
  • 2
  • 13
  • 28
  • 1
    To know why `this` works with `function` check this [Can you bind `this` in an arrow function?](https://stackoverflow.com/questions/33308121/can-you-bind-this-in-an-arrow-function) – Karan Jun 19 '20 at 05:30
  • This is what I was looking for! Also, I left it as es6 function by passing down car object to `setYear` function – scriobh Jun 19 '20 at 05:30