Object.create与新继承混淆

Object.create vs new inheritance confusion

本文关键字:继承 create 新继承 Object      更新时间:2023-09-26

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

这与"new"与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 

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

对于Object.create,由于您没有指定给testObj,因此您正在更改testObj引用的共享对象。

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

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