从使用的Object.create现有创建对象()

问题描述 投票:3回答:4

哎看在MDN Object.create() MDN进出口试图复制他们的榜样之后,但它不工作

这里就是我想和我得到了什么

    const oTest = {a:1,b:2}
 
    const test1 = Object.create(oTest)
 
    console.log(oTest)  //{a: 1, b: 2}
    console.log(test1 ) //{}

我预计test1的安慰{a: 1, b: 2}

javascript object
4个回答
2
投票

正如评论所说,现有的对象作为原型为新创建的对象。所以你看不到它(至少在节点)一个的console.log。尝试在Chrome和将这种该__proto__有你oTest对象。 enter image description here

如果你想在你的新对象复制对象的属性,你可以const test2 = {...oTest}。它是传播运营商:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


0
投票

Object.create(o)创建一个空对象。当然,一个继承属性从o,但这只是意味着,他们可在接入和实际上不被复制到自己的属性。您的控制台只显示自己的属性 - 但如果你展开对象,也应该表现出原型链。

const oTest = {a:1,b:2};
const test1 = Object.create(oTest);

console.log(oTest) // {a: 1, b: 2}
console.log(test1) // {}
console.log(Object.getPrototypeOf(test1) == oTest) // true
console.log(test1.a) // 1

0
投票

如果您有例如Chrome开发者工具检查它,你可以看到对象的原型和它的属性。

或者你也可以console.log(test1.__proto__)查看那些方法。

enter image description here


0
投票

可能是你需要使用Object.assign()来创建现有对象的副本。

成本OTES = {A,1,B 2}

TEST1 =常数Object.assign(OTES)

的console.log(OTES){//答:1,B 2}

的console.log(TEST1)// {一个:1,B:2}

© www.soinside.com 2019 - 2024. All rights reserved.