Last active
March 5, 2018 11:43
-
-
Save web2ls/864d048188a1beafbf2629577b1e5414 to your computer and use it in GitHub Desktop.
JavaScript patterns
This file contains hidden or 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
| //"Module" patterns | |
| const Bucket = (function(){ | |
| let sum = 0; | |
| const goods = []; | |
| return { | |
| printProducts: function() { | |
| goods.forEach(item => console.log(item)); | |
| }, | |
| addProduct: function(product) { | |
| goods.push(product); | |
| sum += product.price; | |
| console.log(goods); | |
| } | |
| } | |
| }()); | |
| const bread = { | |
| name: 'Bread', | |
| price: 20 | |
| }; | |
| const sault = { | |
| name: 'Sault', | |
| price: 30 | |
| }; | |
| Bucket.addProduct(bread); | |
| Bucket.addProduct(sault); | |
| Bucket.printProducts(sault); | |
| //"Singletone" pattern | |
| const Singletone = (function() { | |
| let instance; | |
| function Singletone() { | |
| if (!instance) { | |
| instance = this; | |
| } else { | |
| return instance; | |
| } | |
| }; | |
| Singletone.prototype.connect = function() { | |
| console.log('Yep connected'); | |
| }; | |
| return Singletone; | |
| }()); | |
| const s1 = new Singletone(); | |
| const s2 = new Singletone(); | |
| console.log(s1 === s2); | |
| s1.connect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment