首先,我确实在很多地方搜索过这个,但没有找到足够的答案,但我也意识到这可能只是我的失败。
--这与"new“vs Object.create()创建的对象有关
背景:当使用"new“创建对象时,我得到一个对象,它是用原始属性填充的原始对象的副本,但它是自己的东西。但是,当我使用"Object.create()“创建一个对象时,我会得到一个新的对象,它似乎只是指向指定的原型。当在新对象中指定值时,这似乎不是一个问题,因为新值是在新对象中创建的。但是,当我将键值对放入由new创建的对象中时,它只会影响新对象;但是,如果我对Object.create()创建的对象做同样的事情,它会更改原型,并且所有共享该原型的对象都会受到影响。
问题:这是正确的行为还是我做错了什么?直觉地认为,任何新创建的对象,无论是哪种方法,都是独立的“个体”,并且是单独可变的,除非我显式地更改了原型,但这似乎不是Object.create()所发生的情况。
如何使用Object.create()来创建原型的唯一实例并在不影响原型的情况下影响到内部的对象?或者我应该接受这不是Object.create()的行为,而是使用构造函数吗?
下面是一些代码作为示例:
function NewThing(){
this.testVal = 35;
this.testString = "Default";
this.testObj = {};
}
thing={
testVal: 35,
testString: "Default2",
testObj: {}
}
test1 = new NewThing()
//test1 becomes a new Object with all the properties of NewThing
test2 = Object.create(thing)
// test2 becomes an object that seems to point to the thing object
test3 = Object.create(thing)
// test3 becomes an object that also seems to point to the thing object
test1.testVal = 45
//testVal property of test1 seems changed fine
test2.testVal = 45
//testVal property of test2 seems changed and NOT test 3 which is good
test1.testObj["test"]="is fine"
//puts the pair in the object of test1
test2.testObj["test"]="is NOT fine"
//puts the pair in the PROTOTYPE affecting BOTH test2 and test3 发布于 2015-11-30 00:13:41
NewThing在每次调用时为testObj创建新对象。
使用Object.create时,由于没有分配给testObj,所以需要更改testObj引用的共享对象。
就好像您在NewThing中使用了共享对象一样。
sharedObj = {};
function NewThing(){
this.testVal = 35;
this.testString = "Default";
this.testObj = sharedObj;
}https://stackoverflow.com/questions/33983923
复制相似问题