Last active
January 1, 2019 16:50
-
-
Save SebastianHGonzalez/bedbe21e8314bb8652c38bb0c7abf8a8 to your computer and use it in GitHub Desktop.
first attempt to generalize aspect implementation
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
function aspect(joinPoint, { before, around, after }) { | |
return function (...args) { | |
before && before(this, joinPoint.name, ...args); | |
const result = around ? around(this, joinPoint, ...args) : joinPoint.apply(this, args); | |
after && after(this, joinPoint.name, result, ...args); | |
return result; | |
} | |
} | |
function loggerAspect(joinPoint, logger) { | |
function before() { logger.log("logging before") } | |
function after(context, name, result) { logger.log("logging after", "result:", result) } | |
return aspect(joinPoint, { before, after }) | |
} | |
class Person { | |
constructor(name) { | |
this.name = name | |
} | |
greeting() { | |
return "Hello " + this.name | |
} | |
} | |
const person = new Person("john doe"); | |
person.greeting(); | |
// <- "Hello john doe" | |
// Apply logger aspect | |
Person.prototype.greeting = loggerAspect(Person.prototype.greeting, console) | |
person.greeting(); | |
// logging before | |
// logging after result: Hello john doe | |
// <- "Hello john doe" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment