Object.create() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create and Object.getOwnPropertyDescriptors() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors就是你所需要的。
const obj = JSON.parse(JSON.stringify(d1))
const d3 = Object.create(Dog.prototype, Object.getOwnPropertyDescriptors(obj))
这个和OP的方法的区别在于这个方法设置prototype
原型上的属性,而OP的方法直接在对象上设置属性。当您使用 for-in 循环遍历对象自己的属性时,您可以看到这一点hasOwnProperty()
method:
for (const i in d1) {
if (d3.hasOwnProperty(i)) {
console.log(i)
}
}
用我的方法它只输出_name
,但是用OP的方法它也输出getName
.
很遗憾,Object.getOwnPropertyDescriptors()
是 ECMAScript 2017 的一部分,目前仅在 Firefox 中受支持,因此您需要使用 Babel。
或者,您可以使用Object.setPrototypeOf() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf。它的浏览器支持比Object.getOwnPropertyDescriptors()
,但 MDN 不鼓励这样做,因为它很慢。
const d3 = JSON.parse(JSON.stringify(d1))
Object.setPrototypeOf(d3, Dog.prototype)