Sunday, 29 September 2013

Transparent hierarchical data frames in JavaScript

Transparent hierarchical data frames in JavaScript

Not sure about terminology.
I have a JavaScript "object" with some data:
var parent = { foo: 42, bar: 2.71, baz: 3.14 };
I need to create another JavaScript object that will provide access to the
parent object, while supporting local overrides for parent's entries:
var child = extend(parent, { foo: 1, quo: 2 });
child.bar = 3;
parent.qux = 4;
assert(parent.foo === 42);
assert(child.foo === 1);
assert(parent.bar === 2.71);
assert(child.bar === 3);
assert(parent.baz === 3.14);
assert(child.baz === 3.14);
assert(parent.quo === undefined);
assert(child.quo === 2);
assert(parent.qux === 4);
assert(child.qux === 4);
// NB: I don't care about iteration on these objects.
I need the solution to be as low-overhead as possible while being
cross-browser enough. Copying parent values to the child is too much
overhead.
That is, I'm looking for something akin to Lua metatable chains, but in
JavaScript.
I was reading about [[Prototype]] chains. It looks like the way to go, but
I did not figure out a lightweight way to use them here yet. (__proto__,
as I understand it, is not cross-browser enough.)
Any clues?

No comments:

Post a Comment