Object.create与新继承混淆
Object.create vs new inheritance confusion
首先,我确实在很多地方搜索了这个,但找不到合适的答案,但我也意识到这可能只是我的失败。
这与"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;
}
相关文章:
- 从控制器继承了隔离的作用域以生成可重用的指令
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- 当使用控制器作为语法时,如何从父指令继承属性
- 以jquery方式继承Javascript
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 使用Object.create()的角度服务继承
- 使用Object.create作为原型的原型继承将[Object]作为实例的原型
- 使用 Object.create 进行继承
- 为什么 Object.create 在 JavaScript 中的原型继承方面没有做我所期望的
- Javascript Object.create 不是从父级继承的
- Javascript OOP 继承了 create GLOBAL 对象
- ECMAScript 5定义了用于构造和继承的通用工厂模式[Object.create()]
- 原型继承和Object.create
- Object.create与新继承混淆
- 使用Object.assign和Object.create进行继承
- 是否可以确定使用object创建的对象.create继承了JavaScript中的Array
- Object.create(BaseObject)和util的区别是什么?继承(MyObject BaseObject)
- 没有new或Object.create的原型继承
- JavaScript继承Object.create()未按预期工作
- Object.create与直接原型继承