Skip to content

Instantly share code, notes, and snippets.

@tudorilisoi
Last active October 13, 2020 16:23
Show Gist options
  • Save tudorilisoi/7eafa108e9fc5fe6ed956947b24dc18d to your computer and use it in GitHub Desktop.
Save tudorilisoi/7eafa108e9fc5fe6ed956947b24dc18d to your computer and use it in GitHub Desktop.
JS constructor, factory, class
//*** Object creation
// 1) class syntax , usage: p = new Person('Rex')
class Person {
constructor(name) {
this.name = name
}
sayHello() {
console.log(`Hi, I'm ${this.name}`)
}
}
// 2) constructor function, usage: p = new Person('Rex')
function Person(name) {
this.name = name
}
Person.prototype.hello = function () {
console.log(`Hi, I'm ${this.name}`)
}
//method
const helloMethod = function () {
console.log(`Hi, I'm ${this.name}`)
}
// 3) factory function, usage: p = createPerson('Rex')
function createPerson(name) {
const ret = {
name,
}
ret.hello = helloMethod
return ret
}
const p = createPerson('rex')
p.name = 'XXXX'
p.hello()
//*** functions as arguments and return values for/of other functions
function wrapWithLogging(fn) {
return () => {
console.log(`calling...`)
const ret = fn()
console.log(`returned: ${ret}`)
return ret
}
}
const f1 = wrapWithLogging(wrapWithLogging( ()=> {
return 'F one'
}))
f1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment