ECMA5 Object.create

本文介绍了ECMAScript 5中新增的Object.create方法,详细解释了如何使用此方法创建对象,包括设置原型和属性描述符等内容。通过示例演示了如何利用此方法实现对象继承。

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

Object.create(prototype,descriptors) 是E5中提出的一种新的对象创建方式。
     
 1.参数:
prototype是要继承的原型,如果不是一个子函数,可以传一个null。
descriptors是对象的属性描述符,这个参数是可选的。数据属性是可获取可设置的属性,数据属性描述符包括value,writable,configurable和enumerable特性。如果没有指定,后三个值默认为false。访问器属性包括configurable,enumerable,get和set特性。
  
2.返回的值

一个以prototype为原型并且包含指定属性的新对象。


3.异常

包含以下三种情况:

 (1)prototype不是对象并且不是null
   
 (2)descriptors里面具有value和writable特性,同时还要set和get特性

 (3)descriptors里面具有不是函数的set和get特性

4.示例

(1)
  

    var newObj = Object.create(null, {
            size: {
                value: "large",
                enumerable: true
            },
            shape: {
                value: "round",
                enumerable: true
            }
        });

for (var item in newObject){
       console.log(item);
   }

//size
//shape


 (2)
 
function Person(name){
   this.name=name;
}
 Person.prototype.showName=function(){
     console.log(this.name);
}
var  person1=Object.create(Person.prototype,{
  name:{
    value:"vuturn",
    enumerable:true,
    writable:true
   },
job:{
value:"software engineer",
enumerable:true
}
});

person1.showName();//vuturn
person1.name="John";
person1.showName();//John

person1.job="doctor";

console.log(person1.job);//software engineer

  (3)实现继承
function SuperType(name){
  this.name=name;
}

SuperType.prototype.showName=function(){
  console.log(this.name);
}
function SubType(name){
   SuperType.call(this.name);
}

SubType.prototype=Object.create(SuperType.prototype);

var person=new SubType("vuturn");

person instanceof SubType;
person instanceof SuperType;





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值