Object.create与新的继承混淆

时间:2015-11-29 14:32:13

标签: javascript object inheritance

首先,我确实在很多地方搜索过这个问题,但找不到合适的答案,但我也意识到这可能只是我的失败。

这与“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 

1 个答案:

答案 0 :(得分:0)

NewThing在每次调用时为testObj创建新对象。

使用Object.create,由于您未分配给testObj,因此您正在更改testObj引用的共享对象。

就好像您在NewThing中使用了共享对象:

sharedObj = {};
function NewThing(){
  this.testVal = 35;
  this.testString = "Default";
  this.testObj = sharedObj;
}
相关问题