javascript - Accessors Composition in ES6 Classes -
let's have thing class want both hideable , openable.
using similar approach douglas crockford's object creation through composition, have been able "inherit" multiple classes.
this approach not work accessors (getter/setters).
i need use classes it's requirement. i'm finding duplicating functionality class class, don't want these inherit base class.
any ideas?
the progress have made far in below snippet:
class openable { constructor(isopen = false) { this._isopen = isopen; } isopen() { return this._isopen + ' stupid.'; } set isopen(value) { this._isopen = value; } } class hideable { constructor(ishidden = false) { this._ishidden = ishidden; } ishidden() { return this._ishidden + ' stupid.'; } set ishidden(value) { this._ishidden = value; } } class thing { constructor(config) { let { isopen, ishidden } = config; let openable = new openable(isopen); this.isopen = openable.isopen; let hideable = new hideable(ishidden); this.ishidden = openable.ishidden; } } let thing = new thing({ isopen: true, ishidden: false });
because isopen , ishidden accessors, can't grab copy of them, have access them when want them.
still, can create own isopen, ishidden use underlying ones:
let openable = new openable(isopen); object.defineproperty(this, "isopen", { get: () => openable.isopen, set: value => { openable.isopen = value; } }); let hideable = new hideable(ishidden); object.defineproperty(this, "ishidden", { get: () => hideable.ishidden, set: value => { hideable.ishidden = value; } }); naturally, if lot, you'd want have worker function set rather retyping time:
function wrapproperty(dest, src, name) { object.defineproperty(dest, name, { get: () => src[name], set: value => { src[name] = value; } }); } (or grabbing property descriptor , updating it)
then:
wrapproperty(this, openable, "isopen"); wrapproperty(this, hideable, "ishidden"); i'd question requirement must use class openable , hideable. more mixins me.
Comments
Post a Comment