Created
March 18, 2015 16:12
-
-
Save kl0tl/400f1cd46d95be24bc06 to your computer and use it in GitHub Desktop.
Some fun with the hypothetical ES7 decorators notation (`@xxx`)
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
class Class { | |
@Bound | |
method() {} | |
@Lazy | |
get data() {} | |
} | |
function Bound(prototype, name, descriptor) { | |
const { value, writable, enumerable, configurable } = descriptor; | |
if (typeof value !== 'function') { | |
throw new Error(); | |
} | |
const decoratedDescriptor = { | |
get() { return value.bind(this) } | |
enumerable, configurable | |
}; | |
if (writable) decoratedDescriptor.set = function (newValue) { | |
overrideWith(this, name, newValue) | |
}; | |
return Lazy(prototype, name, decoratedDescriptor); | |
} | |
function Lazy(prototype, name, descriptor) { | |
const { get, set, enumerable, configurable } = descriptor; | |
if (typeof get !== 'function') { | |
throw new Error(); | |
} | |
const decoratedDescriptor = { | |
get() { | |
const value = get.call(this); | |
overrideWith(this, name, value); | |
return value; | |
}, | |
enumerable, | |
configurable | |
}; | |
if (set) decoratedDescriptor.set = set; | |
return decoratedDescriptor; | |
} | |
function overrideWith(target, name, value) { | |
const { set, writable, enumerable, configurable } = Object.getOwnPropertyDescriptor(this, name); | |
const descriptor = { value, writable: writable || Boolean(set), enumerable, configurable }; | |
Object.defineProperty(this, name, descriptor); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment