我的目标是让otherFoo从foo继承,但之后不会继承回父级。我已经尝试了一些使用Object.create的角度,但它继续继承回父。
var foo = { "bar": {"data1":"02", "data2":"03"}, "otherBar":"09"};
var otherFoo = {};
otherFoo.bar = foo.bar;
otherFoo.bar.data1 = "04";
我希望最终结果是
// foo = { "bar": {"data1":"02", "data2":"03"}};
// otherFoo = { "bar": {"data1":"04", "data2":"03"}};
以下是便利性的JSFiddle
答案 0 :(得分:3)
您的意思是Object.assign()吗?
let foo = { "bar": {"data1":"02", "data2":"03"}, "otherBar":"09"};
let otherFoo = Object.assign({}, foo);
foo.otherBar = 10;
console.log(foo);
console.log(otherFoo);
答案 1 :(得分:1)
你可以尝试使用一个类:
function template(data1) {
this.data = { "bar": {"data1": typeof data1 !== 'undefined' ? data1: '02', "data2":"03"}};
}
var foo = new template();
var otherFoo = new template('04');
console.log(foo.data);
console.log(otherFoo.data);
答案 2 :(得分:0)
如果可以使用对象扩展运算符:
var foo = { "bar": {"data1":"02", "data2":"03"}, "otherBar":"09"};
var { otherBar, ...bar } = foo
foo = bar
var fooBar = {
bar: { ...foo.bar, data2: "04" }
}
否则你需要深度克隆你的对象。
答案 3 :(得分:0)
接近Talha的答案,但我认为我只是继续发布它(因为它模仿你的例子,几乎就是你希望数据表示的那样)
const bar = function(data){
this.bar = data;
}
let foo = new bar({"data1":"02", "data2":"03"})
let otherFoo = new bar({"data1":"04", "data2":"03"})
console.log(foo)
console.log(otherFoo)

答案 4 :(得分:0)
这是一个可以深度克隆任何对象的函数,包括循环对象。除了prototype
链中的值之外,它还保留原始对象中的循环引用,而不引用原始对象中的任何值:
function clone (object, objects = new WeakMap()) {
// this will omit copying primitives
if (typeof object !== 'object' && typeof object !== 'function' || object === null) {
return object;
}
if (objects.has(object)) {
return objects.get(object);
}
const proto = Object.getPrototypeOf(object);
const descriptors = Object.getOwnPropertyDescriptors(object);
const copy = typeof object === 'function'
? object.call.bind(object)
: Object.create(proto);
objects.set(object, copy);
Object.values(descriptors).forEach(descriptor => {
if ('value' in descriptor) {
descriptor.value = clone(descriptor.value, objects);
}
});
return Object.defineProperties(copy, descriptors);
}
let foo = { bar: { data1: '02', data2: '03' }, otherBar: '09' };
class Test {
constructor (...args) { this.args = args; }
cool () { return 'feature'; }
}
foo.bar.foo = foo;
foo.bar.bar = foo.bar;
foo.test = new Test('foo', 'bar');
foo.bar.test = foo.test;
foo.bar.func = () => 'func';
console.log(foo);
var otherFoo = clone(foo);
// everything copies as expected
console.log(otherFoo);
console.log(otherFoo.test instanceof Test);
console.log(otherFoo.bar.func() === 'func');
console.log(typeof otherFoo.bar.func === 'function');
// nothing references the original object
console.log(foo !== otherFoo);
console.log(foo.bar !== otherFoo.bar);
console.log(foo.test !== otherFoo.test);
console.log(foo.bar.func !== otherFoo.bar.func);
// doesn't copy prototypes
console.log(foo.test.cool === otherFoo.test.cool);

.as-console-wrapper{max-height:100%!important}