Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Avoiding Positional Arguments in Javascript
/**
Positional arguments in code often become a pain as when something is updated then every instance of
the constructor instance must be updated. Thanks to Sandi Metz's POODR, I became aware of this problem and
thought i'd write a quick gist showing how such a problem could be resolved in Javascript.
*/
// Positional Constructor
function Wallet(license, creditCard, libraryCard) {
this.license = license;
this.creditCard = creditCard;
this.libraryCard = libraryCard;
}
// Positional invocation
// WORKS!
Wallet(new License(), new CreditCard(), new LibraryCard());
// Broken :( Due to unexpexted behavior
Wallet(new License(), new LibraryCard(), new CreditCard());
// Non-Positional Constructor
function Wallet({ license, creditCard, libraryCard }) {
this.license = license;
this.creditCard = creditCard;
this.libraryCard = libraryCard;
}
// Non-Positional invocation
// WORKS!
Wallet({license: new License(), creditCard: new CreditCard(), libraryCard: new LibraryCard()});
// Works too! Yay!
Wallet({license: new License(), libraryCard: new LibraryCard(), creditCard: new CreditCard()});
/**
This approach still won't save you from certain scenarios, but it definitely makes your code base
more maintable.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.