我需要深层复制骨干模型。 clone
方法不进行深层复制,对attributes
对象的引用会被复制到克隆中。我通过以下方式完成了这项工作:
var model = Backbone.Model();
// modifying model
var clone = _.merge(Object.create(Object.getPrototypeOf(model)), model);
还有更好的选择吗?
答案 0 :(得分:0)
还有更好的选择吗?
使用benchmark.js来比较此方法与本机方法的效果:
GROUP BY
var bench1 = new Benchmark(
{'fn':merge_object, 'cycles':0,'count':1,'name':'merge','async':true}
);
var bench2 = new Benchmark(
{'fn':parse_object, 'cycles':0,'count':1,'name':'parse','async':true}
);
var foo = {"bar": {"baz": {"bop": "zero"} } };
function merge_object()
{
var clone = _.merge(Object.create(Object.getPrototypeOf(foo)), foo);
}
function parse_object()
{
new Backbone.Model(JSON.parse(JSON.stringify(foo)))
}
function log(result){console.log(JSON.parse(JSON.stringify(result)))};
bench1.on('complete', log);
bench2.on('complete', log);
bench1.run();
bench2.run();
<强>参考强>