-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory-functions.js
executable file
·49 lines (38 loc) · 1.03 KB
/
factory-functions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Factory Function - functions that return objects
const personFactory = (name, age) => {
const sayHello = () => console.log(`hello ${name}`)
return { name, age, sayHello }
// ^^^SHORTHAND FOR: return {name: name, age: age, sayHello: sayHello};
}
const john = personFactory('john', 32)
console.log(john.name)
john.sayHello()
// Constructor Function (BAD)
const Person = function (name, age) {
this.sayHello = () => console.log(`hello ${name}`)
this.name = name
this.age = age
}
const jack = new Person('jack', 32)
console.log(jack.name)
jack.sayHello()
// Class
class PersonClass {
constructor(name, age) {
this.name = name
this.age = age
}
sayHello() {
console.log(`hello ${this.name}`)
}
}
const kate = new PersonClass('kate', 32)
console.log(kate.name)
kate.sayHello()
const fruitFactory = (name, color) => {
const sayName = () => console.log(`This fruit is a ${name}`)
return { name, color, sayName }
}
const banana = fruitFactory('banana', 'yellow')
console.log(banana.name, banana.color)
banana.sayName()