Javascript Objects
info: https://www.youtube.com/watch?v=XoQKXDWbL1M&list=PLQ9UGuDU7vgBIbJN5GE9voObuMZtohZIr&index=13&t=5s info: https://www.youtube.com/watch?v=nnwD5Lwwqdo&t=5s
| // Various ways of creating objects | |
| // a. | |
| const Person = function (name) { | |
| this.name = name; | |
| this.getName = function() { | |
| console.log(this.name); | |
| } | |
| } | |
| const jose = new Person('guillaume'); | |
| jose.getName(); | |
| // b. | |
| const Person2 = { | |
| firstName: "John", | |
| getName() { | |
| console.log(this.firstName); | |
| } | |
| }; | |
| Person2.getName(); | |
| // Factory | |
| const createMonster = (name) => ({ | |
| name, | |
| getName() { | |
| console.log(name); | |
| } | |
| }); | |
| const Monster = createMonster('lolz'); | |
| const Monster2 = createMonster('Coucou'); | |
| Monster.getName(); | |
| Monster2.getName(); | |
| // Closure | |
| const multiplyByTwo = (a) => { | |
| return function (b) { | |
| console.log(a + b); | |
| }; | |
| }; | |
| multiplyByTwo(2)(3); | |
| const intermediateStep = multiplyByTwo(2); | |
| intermediateStep(3); | |
| // Composition | |
| const flyer = ({ name }) => { | |
| return { | |
| fly: () => console.log(`${name} flew`), | |
| } | |
| }; | |
| const huger = ({ name }) => { | |
| return { | |
| hug: () => console.log(`${name} huggued`), | |
| } | |
| }; | |
| const Monster3 = (name) => { | |
| const monster = { name }; | |
| return { | |
| ...flyer(monster), | |
| ...huger(monster), | |
| } | |
| } | |
| const obj = Monster3('Herve'); | |
| obj.fly(); | |
| obj.hug(); |