Created
March 27, 2016 17:15
-
-
Save alexnm/bee023ca0ce2b79abd0f to your computer and use it in GitHub Desktop.
Example of factory based object creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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