Last active
September 11, 2020 13:00
-
-
Save ant1m4tt3r/6c101a3c706759913b50dcd2db906a8a to your computer and use it in GitHub Desktop.
Object as HOF
This file contains 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
// HOFCreator.js ----------- | |
const HOFCreator = { | |
createProxy(methods, dataContext) { | |
const handler = { | |
apply (_, __, property) { | |
return function (...args) { | |
return methods[property].call(dataContext, ...args) | |
} | |
}, | |
} | |
return new Proxy(() => {}, handler) | |
} | |
} | |
// ------------------------- | |
// Person.js --------------- | |
const PersonMethods = { | |
getFullName () { | |
return this.name + ' ' + this.lastName | |
}, | |
setFirstName (name) { | |
this.name = name | |
}, | |
setLastName (lastName) { | |
this.lastName = lastName | |
} | |
} | |
function Person (name, lastName) { | |
const PersonContext = {name, lastName} | |
return HOFCreator.createProxy(PersonMethods, PersonContext) | |
} | |
// ------------------------- | |
// main.js ----------------- | |
const person = Person('Hugo', 'Azevedo') | |
console.log(person('getFullName')()) // 'Hugo Azevedo' | |
person('setFirstName')('Me segue no twitter') | |
person('setLastName')('@hugoidont') | |
console.log(person('getFullName')()) // 'Me segue no twitter: @hugoidont' | |
// ------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment