-1

I would like to refactor my javascript code with an function.

ingos - is a name of the company and I have 5th of similar code parts.

    $('#ingosRegularPrice').removeClass("inactive");
    $('#ingosActivePrice').removeClass("inactive");
    $('#ingosRegularPrice .btn span').text(ingosPrice);
    $('#ingosActivePrice .btn span').text(ingosPrice * params.ingos.programB);

with something like

  function setPriceActive(company){
    $('#'+ company + 'RegularPrice').removeClass("inactive");
    $('#'+ company + 'ActivePrice').removeClass("inactive");
    $('#'+ company + 'RegularPrice .btn span').text(companyPrice);
    $('#'+ company + 'ActivePrice .btn span').text(ingosPrice * params.company.programB);
  }

But I get an reference error that 'company' variable doesn't exist. How I can use function params as an text reference and part of other variable name?

Thanks

Sergey Khmelevskoy
  • 2,429
  • 3
  • 19
  • 43

1 Answers1

2

change:

params.company.programB

to:

params[company].programB

MDN Article on Object Notation

topheman
  • 7,422
  • 4
  • 24
  • 33
Joe
  • 80,724
  • 18
  • 127
  • 145
  • Really? No duplicate worth posting? ;) – mplungjan Feb 14 '17 at 18:29
  • do you mean params[company].programB – Vladu Ionut Feb 14 '17 at 18:30
  • All questions are duplicates in some way. However, it's clear with dot notations. Thanks. I just didn't know how the formulate the question on search. What about variable names? text(ingosPrice) . How do I use (companyPrice) instead? – Sergey Khmelevskoy Feb 14 '17 at 18:59
  • Sergey, `this[company + "Price"]` should work. `this` would be the context depending where you declared the variable ignosPrice. – Joe Feb 14 '17 at 21:40