i trying achieve following: store data subclasses in superclass.
the following example works in practice have been told use of static get|set x() {}
in example below not correct since setter
method uses this._data
out of context of immediate function, i.e. not passed function argument, , such setter no longer static.
example:
'use strict'; // base.js class base { constructor () {} static data () { return this._data; } static set data (newdata) { // merge newdata existing data return this._data = _.assign({}, this._data, newdata); } } //------------------------------------------------------------------------------ // a.js class extends base { constructor () { super(); } add (obj) { base.data = obj; } } let = new a(); a.add({b: 'test'}); // -> expectation: base.data = { b: 'test' } //------------------------------------------------------------------------------ // b.js class b extends base { constructor () { super(); } add (str) { base.data = { somefixedkey: str }; } } let b = new b(); b.add('hello'); // -> expectation: base.data = { b: 'test', somefixedkey: 'hello' }
what trying achieve here have single superclass sits @ base of multiple other subclasses , these subclasses can store data in superclass pubsub notifications whenever data changes , able send full data object containing data stored subclasses pubsub event.
if setter/getter in base.js
not static
, issue having a.js
track a.js
's data , not know b.js
's data.
if indeed invalid use case of static getter/setter accessors, may have split out data store ability separate singleton tracks data , dependency subclasses. not end of world, since "works" learn more use case static getters , setters.
thanks taking look.
update: here example js fiddle demonstrates (in reduced test case how should work:
- "working" example using
static
: https://jsbin.com/koruba/2/edit?js,console - "non working" example not using
static
: https://jsbin.com/koruba/3/edit?js,console
the question is: regardless of whether singleton/pubsub store better, use of static
within filters
superclass valid? static set data (newdata) {}
method since accesses this._data
, have been told method static
must not access outside immediate function , since this._data
not passed method argument should not use static
here.
"non working" example not using
static
yes, not using static
properties set on each instance separately, aren't shared anything.
i have been told method
static
must not access outside immediate function , sincethis._data
not passed method argument should not usestatic
here.
whoever told referred instance properties. if call static method instance method, cannot access instance's properties using this
of course, that's whole point of static methods.
however, in every other method call can access properties of object called upon, static method class (constructor function) itself. using this._data
access static base._data
property - , want in use case, it's totally fine use it.
Comments
Post a Comment