Creating new objects using object literals

左心房为你撑大大i 提交于 2019-12-22 18:13:06

问题


I have the following object literal:

var a = {a:1,b:2}

now I want another instance of the same object. If I'm using a constructor, I can do this using the 'new' operator, ie:

b = new a(); 

How to create a new instance of an object using object literals?


回答1:


The simplest way would be with Object.create

var b = Object.create(a);

console.log(b.a); //1
console.log(b.b); //2

DEMO

And of course if you need to support older browsers, you can get the MDN shim for Object.create here



来源:https://stackoverflow.com/questions/9205136/creating-new-objects-using-object-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!