模块 ringo/utils/objects
添加用于处理 JavaScript 对象的实用程序函数
clone (object, circular, depth, prototype)
创建给定对象的深层克隆(完整副本)。
它通过跟踪访问的属性来支持使用循环引用来克隆对象。 只有当克隆的对象不能通过预知持有任何循环引用时,可以关闭追踪以节省CPU和内存。
Example
let objects = require("ringo/utils/objects");
let a = [1, 2, 3];
// shallow clone: b.a and c.a will share the same array
let b = objects.clone(a);
a[0] = 100;
console.dir(a); // -> [ 100, 2, 3 ]
console.dir(b); // -> [ 1, 2, 3 ]
let root = { simple: 1 };
let circle = { circ: root };
root.circle = circle;
let copy = objects.clone(root);
console.dir(root); // -> { simple: 1, circle: { circ: [CyclicRef] }}
console.dir(copy); // -> { simple: 1, circle: { circ: [CyclicRef] }}
// endless loop, throws a java.lang.StackOverflowError
let danger = objects.clone(root, false);
// limiting the depth might lead to shallow clones!
let tree = { root: 1, a: { b: { c: { d: { e: "foo" } } } } };
let fullClone = objects.clone(tree);
let shallowClone = objects.clone(tree, true, 1);
tree.root = 2; // depth = 1
tree.a.b.c.d.e = "bar"; // depth = 5
console.log(tree.root); // --> 2
console.dir(tree.a.b.c.d); // --> { e: 'bar' }
console.log(fullClone.root); // --> 1
console.dir(fullClone.a.b.c.d); // --> { e: 'foo' }
console.log(shallowClone.root); // --> 1
console.dir(shallowClone.a.b.c.d); // --> { e: 'bar' }
Parameters
Object | object | the object to clone |
Boolean | circular | (optional, default true) true if the object to be cloned may contain circular references |
Number | depth | (optional, default Infinity) limits the non-shallow clone of an object to a particular depth |
Object | prototype | (optional) sets the prototype to be used when cloning an object |
Returns
Object | the clone object |
See
merge (obj...)
创建一个新对象,如同提供对象的按键联合一样。 只要某个键存在于较早对象中已存在的较晚对象中,则较早对象的相应值优先。
Example
const a = { "k1": "val-A" };
const b = { "k1": "val-B", "k2": "val-B" };
const c = { "k1": "val-C", "k2": "val-C" };
// result: { k1: 'val-A', k2: 'val-B' }
const result = objects.merge(a, b, c);
Parameters
Object... | obj... | The objects to merge |