Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Last active May 17, 2018 12:12
Show Gist options
  • Save alexandrebodin/0c5c6ae8b72b72ea4e2d2e84843361bf to your computer and use it in GitHub Desktop.
Save alexandrebodin/0c5c6ae8b72b72ea4e2d2e84843361bf to your computer and use it in GitHub Desktop.
Context binding vs factory

Comparing two different ways to do dependency injection

Simple factory (straight forward)

 const createStuff = (dependencies) => {
 
  const newStuff = {
    //... using the dependencies
  }
  
  return newStuff;
};

Function binding (arguably make the module more readable)

// stuff.js
const stuffApi = {
  f1(dependencies, ...args) {
    // using deps
  },
  f2(dependencies, ...args) {
    // using deps
  }
}

// createStuff
// exemple implementation, do not use
const createStuff = (deps) => {
 return Object.assign({}, Object.keys(stuff).reduce((acc, key) => {
   if (typeof acc[key] === 'function') {
    acc[key] =  stuff[key].bind(acc, deps);
   } else {
    acc[key] = stuff[key]
   }
  return acc
 }, {}));
}
@alexandrebodin
Copy link
Author

Would love to get an idea on what people think of these two patterns :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment