Created
September 22, 2024 10:28
-
-
Save vladimir-ivanov/300de5c7a83da109b42b1aa06e7127a4 to your computer and use it in GitHub Desktop.
proxy and method decorator sequence
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 methodDecorator(target, name, descriptor) { | |
const method = descriptor.value; | |
descriptor.value = function (...args) { | |
method.apply(this, args); | |
return this; | |
}; | |
} | |
class Person { | |
isSignedIn = false; | |
@methodDecorator | |
signIn(firstName, lastName) { | |
this.isSignedIn = true; | |
console.log('signIn end', firstName, lastName); | |
return true; | |
} | |
} | |
class PersonVlad extends Person { | |
isVlad = true; | |
} | |
const adapter = (instance) => { | |
const someHandler = { | |
get(target, prop, receiver) { | |
if (target[prop] instanceof Function) { | |
return function (...args) { | |
target[prop].call(this, ...[this, ...args]); | |
}; | |
} | |
return Reflect.get(target, prop, receiver); | |
}, | |
}; | |
return new Proxy(instance, someHandler); | |
}; | |
const p = adapter(new PersonVlad()); | |
p.signIn('john', 'smith'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment