Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active April 30, 2021 19:47
Show Gist options
  • Select an option

  • Save GGrassiant/ff7793e6948ace92499e1c7f3f1c55f0 to your computer and use it in GitHub Desktop.

Select an option

Save GGrassiant/ff7793e6948ace92499e1c7f3f1c55f0 to your computer and use it in GitHub Desktop.
Javascript Objects
// 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment