Skip to content

Instantly share code, notes, and snippets.

@alexnm
Created March 27, 2016 17:15
Show Gist options
  • Save alexnm/bee023ca0ce2b79abd0f to your computer and use it in GitHub Desktop.
Save alexnm/bee023ca0ce2b79abd0f to your computer and use it in GitHub Desktop.
Example of factory based object creation
function createProduct( initialStock ) {
let stock = initialStock;
return {
/* ... extra fields omitted for simplicity ... */
updateStock( newStock ) {
stock += newStock;
},
getStock( ) {
return stock;
}
}
};
const product = createProduct( 4 );
console.log( product.stock ); // undefined!
console.log( product.getStock( ) ); // 4
product.updateStock( 3 );
console.log( product.getStock( ) ); // 7
const product2 = createProduct( 0 );
console.log( product2.getStock( ) ); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment