gabrielcsapo / gabrielcsapo/json-ex

[Proposal] Class instance plus ancestry

Open
#1 3 comments 0 reactions 1 assignee Claimed by @gabrielcsapo View on GitHub
enhancement
Dominant language
JavaScript
Stars
2
Forks
2
PR merge metrics
No merged PRs in 30d

Description

Objects that are instances of any given type, typically class instances, should also serialize their constructor chain back to ECMA script types; i.e. Function. For example

```javascript
let instance;
class A {}
class B extends A {}
class C extends B {}

instance = new C();

function constructLineage(instance) {
const lineage = [];

for (
let ancestor = instance.constructor;
ancestor !== Function.prototype;
ancestor = Reflect.getPrototypeOf(ancestor)
) {
lineage.push(ancestor)
}

return lineage;
}

constructLineage(instance); // [ [Function: C], [Function: B], [Function: A] ]
```

Given the code above you have the lineage of a given class instance. In order to accurately rebuild this object in a different environment, you'll need to persist those classes (via toString()) and recreate them before recreating the object in question if the target environment does not already contain those object definitions.

Perhaps it'll end up being something like
```javascript
{
...
classInstance: [{instanceProp: 'value'}, [C.toString(), B.toString(), A.toString()]]
...
}
```

Where when parsed, C, B, and A will be recreated if necessary. It is arguable as to whether these need to be created globally or within an iffy or something of that nature to protect scope creep. Then afterwards follow up with a `let instance = Object.create(C); Object.assign(instance, classInstance[0])` thereby creating a new instance of C with its prototype chain intact and then doing an Object.assign on top to copy the previous state of the object instance.

Afterwards the following should work

```javascript
instance instanceof C // true
instance instanceof B // true
instance instanceof A // true

// the properties of instance and classInstance should match
// but instance !== classInstance
```

*I may be missing some details here; namely `Reflect.getPrototypeOf` returns the prototype, not the constructor. There may be some tweaking needed here.*

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.