仅获取对象的非原型属性

时间:2019-04-12 15:30:04

标签: javascript prototype ecmascript-5

是否可以创建仅包含对象非原型属性的JS对象的副本?

赞:

Input

1 个答案:

答案 0 :(得分:3)

您可能知道,

对象是原型链接的-因此它们实际上没有拥有原型属性。它们链接到另一个具有属性的对象,并且当找不到属性时,系统会查找链。因此,您无法删除对象没有的东西。

可以,但是可以中断链并使用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())