gpt4 book ai didi

javascript - 仅获取对象的非原型(prototype)属性

转载 作者:行者123 更新时间:2023-11-28 17:06:53 24 4
gpt4 key购买 nike

有没有办法创建一个仅包含该对象的非原型(prototype)属性的 JS 对象的副本?

像这样:

 var copy = object.onlyOwnProperties();

最佳答案

正如您可能知道的那样,对象是原型(prototype)链接的 - 因此它们实际上具有原型(prototype)属性。它们链接到另一个具有属性的对象,当系统找不到属性时,系统会查找链。所以你不能删除对象没有的东西。

但是,您可以打破链条并使用Object.create(null)创建一个不与任何内容链接的对象。例如:

let o = {
name: "Mark",
trade: "Pirate"
}
// o is linked to the Object prototype and
// gets these props from the Object
console.log(Object.getOwnPropertyNames(o.__proto__))

// which means it has things like toString()
console.log(o.toString())

// bare is a stand alone with no prototype
// it will ONLY have the two props
let bare = Object.assign(Object.create(null), o)
console.log(bare.__proto__)

// no toString or anything else
console.log(bare.toString)

// just original props
console.log(bare.name)

也许这太极端了,您确实想要对象方法,但别无其他。在这种情况下,您可以使用对象文字来Object.assign:

let o = {
name: "Mark",
trade: "Pirate"
}

let child = {
childProp: "someVal"
}


Object.setPrototypeOf(child, o)

// child gets o props through prototype
console.log("from prototype:", child.name)

// make an object with only child props
// that is still linked to the Object prototype
let bareChild = Object.assign({}, child)

// no props from o
console.log("from prototype:", bareChild.name)

// just it's own
console.log("own prop:", bareChild.childProp)

// but this still works:
console.log("toString", bareChild.toString())

关于javascript - 仅获取对象的非原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55655020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com