当传递一个对象作为参数并使用它通过 Object.create 创建一个单独的对象时,你会得到一个空对象。但是,如果您随后使用这个新对象来引用在初始对象中设置的特定参数,您将获得初始对象的参数值。我希望这些值包含在新对象中,或者至少无法在其中访问。var o = { baz: [] };o.rrr = { a: 1 };console.log( o, '"o" before timeout called' );setTimeout(function() { n(o) }, 1000); // setting delayfunction n(x) { console.log( 'x - what we passed', x ); var obj = Object.create( x ); console.log( obj, '"obj" before enhancements is empty' ); console.log( obj.rrr, 'but "obj.rrr" do exist' ); obj.baz = []; obj.baz.push( 'new value' ); console.log( obj, '"obj" after enhancements contain "baz" only' ); console.log( obj.rrr, 'but "obj.rrr" still exist' ); console.log( o, '"o" after timeout ended' ); console.log( '---- THE END ----' );}console.log( o, '"o" after timeout called' );为何如此?你能在保持结构的同时摆脱这些引用吗?您是否可以从一开始就在新对象中设置这些值(例如克隆它)?
1 回答

慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
该Object.create()
方法创建一个新对象,x
用作新创建对象的原型。因此,该属性rrr
直接不存在于obj
. 它存在于[[Prototype]]
(或__proto__
)
var x = { prop: 1 }
var y = Object.create(x)
console.log(y.prop) // 1
console.log("prop" in y) // true
console.log(y.__proto__ === x) // true
console.log(y.hasOwnProperty("prop")) // false
所述in
如果指定的属性是在指定的对象或操作员返回true其原型链。因此,在这种情况下,它返回 true。
但是,hasOwnProperty()
另一方面,该方法返回一个布尔值,指示对象是否有一个属性作为它自己的属性。这就是为什么y.hasOwnProperty("prop")
即使y.prop
返回 1也返回 false 的原因。
如果要直接在 中获取属性y
,可以Object.assign()
改用。这会将所有可枚举的自身属性复制x
到一个空的目标对象中。
var x = { prop: 1 }
var y = Object.assign({}, x)
console.log(y.prop) // 1
console.log(y.hasOwnProperty("prop")) // true
添加回答
举报
0/150
提交
取消