DEV Community

Cover image for JS Refactoring Combo: Inline Function as Method
Lars Grammel for P42

Posted on • Edited on • Originally published at p42.ai

JS Refactoring Combo: Inline Function as Method

Sometimes functions are only used as property values. In such cases, you can convert the functions into methods.

Before (Example)

function aFunction(aParameter) {
  doSomething(aParameter);
}

const anObject = {
  aMethod: aFunction
};
Enter fullscreen mode Exit fullscreen mode

Refactoring Steps

Inline Named Function as Method

💡  The refactoring steps are using P42 JavaScript Assistant v1.109

  1. Convert the named function into a variable that contains the function expression
  2. Inline the variable
  3. Convert the function to an object method

After (Example)

const anObject = {
  aMethod(aParameter) {
    doSomething(aParameter);
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
evasteps profile image
Eva Lam

That’s cool. Haven’t thought of this way of writing. Thanks so much for sharing. Insightful ! And the series allows me to learn how to write cleaner code