Last active
February 23, 2017 16:18
-
-
Save Zaggen/382ce8791d536190b9ba9783c805e745 to your computer and use it in GitHub Desktop.
Traits decorator
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
declare const _: _.LoDashStatic | |
export function traits(...traitsList) { | |
return function decorator(constructor: any) { | |
const mergedTraits = _.extend.apply(_, traitsList) | |
const {prototype} = constructor | |
const {__proto__} = constructor.prototype | |
const prototypeClone = _.clone(prototype) // We use a clone to avoid getting properties on the proto chain | |
constructor.prototype = _.extend(prototype, mergedTraits, prototypeClone) | |
constructor.prototype.constructor = constructor | |
constructor.prototype.__proto__ = __proto__ | |
constructor.prototype._traits = mergedTraits | |
} | |
} | |
// Usage | |
/* | |
import {movable, killable} from 'game-traits' | |
@traits(movable, killable) | |
class Player { | |
// We can override traits inherited methods (kill comes from killable) and call the original method via this._traits | |
kill(): void{ | |
console.log('Player is about to die') | |
this._traits.kill.call(this) // Unless you know for sure that the traitFn does not have side effects use with .call or .apply | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment