使用对象字面量创建新对象 [英] Creating new objects using object literals

查看:160
本文介绍了使用对象字面量创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象字面量:

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

现在我想要另一个相同对象的实例。如果我使用一个构造函数,我可以使用'new'运算符,例如:

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?

推荐答案

最简单的方法是使用 Object.create

var b = Object.create(a);

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

DEMO

当然,如果您需要支持旧版浏览器, / a>

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

这篇关于使用对象字面量创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆