JavaScript 中的透明分层数据帧

Transparent hierarchical data frames in JavaScript

本文关键字:分层 数据帧 透明 JavaScript      更新时间:2023-09-26

不确定术语。

我有一个带有一些数据的JavaScript"对象":

var parent = { foo: 42, bar: 2.71, baz: 3.14 };

我需要创建另一个 JavaScript 对象,该对象将提供对父对象的访问,同时支持父条目的本地覆盖:

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.

我需要解决方案尽可能低开销,同时足够跨浏览器。将父值复制到子值开销太大。

也就是说,我正在寻找类似于Lua元表链的东西,但是在JavaScript中。

我正在阅读有关[[Prototype]]链条的信息。看起来这是要走的路,但我还没有找到在这里使用它们的轻量级方法。(据我了解,__proto__不够跨浏览器。

有什么线索吗?

通过将初始值设定项拖放到子对象,我能够想出这个(更新,感谢@FelixKling):

var wrap = function(parent) 
{
  var child = function() { };
  child.prototype = parent;
  return new child();
}

可以进一步改进吗?

下面是一个 JSFiddle: http://jsfiddle.net/b5Q4n/2/

请注意,正如注释中所建议的,有一个JS函数,几乎可以执行所需的操作:Object.create:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create