Update 2, added Gist:
Question: Can derived classes have static get
methods?
3 files here, with attempted use of static get
method in a derived class. It works correctly when accessed inside the class' .es6
file, but doesn't when imported for tests.
I'm just getting my head around ES6 class syntax, but am strong/comfortable in ES5 prototypal inheritance. I'm working on a set of tree data structures. Using Babel.
I have a derived class, RBTree: (see code below)
I want RBTree to have a static get
method, that simply serves as a pointer/property to a null node I have already created. Say I have imported that node from another file, and it is called NULL_POINTER
.
How do I get this static get method to return NULL_POINTER
?
When I import it and try to access like so above, .null
returns undefined
.
I also have tried modifying RBTree outside of the class expression (RBTree.nullPointer =
//...), which does not work.
Update 1:
Renamed some things. Code updated to reflect naming.
I have a working implementation of my original test spike. Here are the relevant files:
RBTree.es6
import {NULL_POINTER} from 'file/with/null/pointer'
export const _NULL_SENTINEL = new RBNode()// constructs the null node
export class RBTree extends BST {
constructor() {
//...super call
}
//...
static get _nil() {
return _NULL_SENTINEL;
}
}
In my Jest testfile:
const RBTree = require('../../../src/binary_trees/RBTree');
const RBNode = require('../../../src/binary_trees/RBNode');
When I step through the tests with with node-inspector:
1. At the bottom of RBTree.es6, RBTree._nil works correctly.
2. If I place a debugger after the lines in the testfile, RBTree._nil returns undefined
.
3. RBTree._NULL_SENTINEL is the same object.
1 and 3 are working as expected.
Is the reason behind 2, that RBTree's static get
function is running in a different scope and no longer has access to _NULL_SENTINEL
? (due two separate export
s?)
I'd want to attach something to the RBTree object such that the static get
will work, but I'd prefer it not to be a pointer on this
.
You are not importing the classes correctly. Since you are using a named export, you have to use a named import. As you can see through RBTree._NULL_SENTINEL
, all the exports become properties of module. (why would _NULL_SENTINEL
be a static property of the class RBTree
? You are never assigning it to RBTree
)
With ES6 it would be
import {RBTree} from '../../../src/binary_trees/RBTree';
and with CommonJS:
const RBTree = require('../../../src/binary_trees/RBTree').RBTree;