Object.create()方法浅谈

本文详细解析了ECMAScript5中Object.create()方法的使用,介绍了如何通过此方法实现原型式继承,包括如何创建新对象并指定其原型,以及如何定义新对象的额外属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Object.create()方法是ECMAScript5中新增的,用来规范化原型式继承的。
这个方法接收两个参数,一个是用作新对象原型的对象,和一个为新对象定义额外属性的(可选)对象。

var person = {
  name : "Nicholas",
  friends : ["John", "Jane"]  // 引用类型值属性共享
}

var onePerson = Object.create(person);  // onePerson继承person对象
onePerson.name = "Greg";
onePerson.friends.push("Mike");
console.log(onePerson.name);  // Greg
console.log(onePerson.friends);  // ["John", "Jane", "Mike"]

var anotherPerson = Object.create(person);
console.log(anotherPerson.name);  // Nicholas
anotherPerson.friends.push("Jacky");
console.log(anotherPerson.friends);  // ["John", "Jane", "Mike", "Jacky"]

// 第二个参数对象格式与Object.defineProperties()方法的第二个参数格式相同
var theOtherPerson = Object.create(person, {
              name : {
                configurable : false,  // 不可修改
                value : "Greg"
              }
});
console.log(theOtherPerson.name);  // Greg
theOtherPerson.name = "Bob";  // 失效
console.log(theOtherPerson.name);  // Greg

new Object()方法的实质是,使用引用类型Object的构造函数创建了一个新的实例,这个实例拥有Object默认的方法如toString、toLocaleString等。

 

转自:https://www.cnblogs.com/lina6251125/p/6391714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值