Last active
February 15, 2017 11:23
-
-
Save davestewart/4d970f013b7b2697db490c3a1ad12f3b to your computer and use it in GitHub Desktop.
JavaScript decorator function
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
Foo > 1 | |
Bar > 1 | |
Bar (doubled) > 2 | |
Bar (doubled, default message) > New value is: 2 | |
Bar (doubled, custom message) > New custom value is: 2 | |
Bar (doubled, default message, uppercase) > NEW VALUE IS: 2 | |
Bar (doubled, custom message, uppercase) > NEW CUSTOM VALUE IS: 2 |
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
/** | |
* Decorator function | |
* | |
* Decorates any object method, passing the last result to following decorations as the first argument | |
* Additional arguments are passed after that, allowing all arguments to be passed to passed all decorations | |
*/ | |
function decorate(obj, prop, fn) { | |
var fnObj = obj[prop] | |
obj[prop] = function () { | |
var result = fnObj.apply(obj, arguments) | |
return fn.apply(obj, [result, ...arguments]) | |
} | |
} | |
/** | |
* Decorator example | |
* | |
* Will create two instances of a base class, and apply multiple decorations to the second | |
*/ | |
// base class | |
function Foo (value) { | |
this.value = value || 0; | |
this.getValue = function () { | |
return this.value; | |
} | |
} | |
// create first instance | |
var foo = new Foo(1) | |
console.log('Foo >', foo.getValue()) | |
// create second instance | |
var bar = new Foo(1) | |
console.log('Bar >', bar.getValue()) | |
// decoration 1 (doubles the result) | |
decorate(bar, 'getValue', function (original) { | |
return original * 2; | |
}) | |
console.log('Bar (doubled) >', bar.getValue()) | |
// decoration 2 (adds a message) | |
decorate(bar, 'getValue', function (original, message) { | |
return (message || 'New value is: ') + original; | |
}) | |
console.log('Bar (doubled, default message) >', bar.getValue()) | |
console.log('Bar (doubled, custom message) >', bar.getValue('New custom value is: ')) | |
// decoration 3 (converts to uppercase) | |
decorate(bar, 'getValue', function (original, message) { | |
return original.toUpperCase(); | |
}) | |
console.log('Bar (doubled, default message, uppercase) >', bar.getValue()) | |
console.log('Bar (doubled, custom message, uppercase) >', bar.getValue('New custom value is: ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment