Created
June 20, 2019 07:05
-
-
Save nash403/2ec0f6bd1d3d9021fb13ede69d9ca55c to your computer and use it in GitHub Desktop.
JS Decorators How to example
This file contains hidden or 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
// Prop/Method Decorator with no arguments | |
function logDecorator(t, n, descriptor) { | |
const original = descriptor.value; | |
if (typeof original === 'function') { | |
descriptor.value = function(...args) { | |
console.log(`Arguments: ${args}`); | |
try { | |
const result = original.apply(this, args); | |
console.log(`Result: ${result}`); | |
return result; | |
} catch (e) { | |
console.log(`Error: ${e}`); | |
throw e; | |
} | |
} | |
} | |
return descriptor; | |
}; | |
/** Usage | |
* | |
* @logDecorator | |
* function toto () {} | |
*/ | |
// Prop/Method Decorator with a 'name' Arguments | |
function logDecoratorWithArgs(name) { | |
function decorator(t, n, descriptor) { | |
const original = descriptor.value; | |
if (typeof original === 'function') { | |
descriptor.value = function(...args) { | |
console.log(`Arguments for ${name}: ${args}`); | |
try { | |
const result = original.apply(this, args); | |
console.log(`Result from ${name}: ${result}`); | |
return result; | |
} catch (e) { | |
console.log(`Error from ${name}: ${e}`); | |
throw e; | |
} | |
} | |
} | |
return descriptor; | |
} | |
} | |
/** Usage | |
* | |
* @logDecoratorWithArgs('some name') | |
* function toto () {} | |
*/ | |
// Class decorator | |
function log(Class) { | |
return (...args) => { | |
console.log(args); | |
return new Class(...args); | |
}; | |
} | |
/** Usage | |
* | |
* @log | |
* class Example { | |
* constructor(name, age) { | |
* } | |
* } | |
* | |
* const e = new Example('Graham', 34); | |
* // [ 'Graham', 34 ] | |
* console.log(e); | |
* // Example {} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment