一种新的javascript对象创建方式Object.create()
Object.create()是什么?
Object.create(proto[,propertiesObject])是E5中提出的一种新的对象创建方式,第一个参数是要继承的原型,如果不是一个子函数,可以传一个null,第二个参数是对象的属性描述符,这个参数是可选的。
例如:
functionCar(desc){ this.desc=desc; this.color="red"; } Car.prototype={ getInfo:function(){ return'A'+this.color+''+this.desc+'.'; } }; //instantiateobjectusingtheconstructorfunction varcar=Object.create(Car.prototype); car.color="blue"; alert(car.getInfo());
结果为:Ablueundefined.
1、propertiesObject参数的详细解释:(默认都为false)
数据属性:
- writable:是否可任意写
- configurable:是否能够删除,是否能够被修改
- enumerable:是否能用forin枚举
- value:值
访问属性:
- get():访问
- set():设置
2、例子:直接看例子就知道怎么用。
<!DOCTYPEhtml> <html> <head> <title>yupeng'sdocument</title> <metacharset="utf-8"/> </head> <body> <scripttype="text/javascript"> varobj={ a:function(){ console.log(100) }, b:function(){ console.log(200) }, c:function(){ console.log(300) } } varnewObj={}; newObj=Object.create(obj,{ t1:{ value:'yupeng', writable:true }, bar:{ configurable:false, get:function(){returnbar;}, set:function(value){bar=value} } }) console.log(newObj.a()); console.log(newObj.t1); newObj.t1='yupeng1' console.log(newObj.t1); newObj.bar=201; console.log(newObj.bar) functionParent(){} varparent=newParent(); varchild=Object.create(parent,{ dataDescriptor:{ value:"Thispropertyusesthisstringasitsvalue.", writable:true, enumerable:true }, accessorDescriptor:{ get:function(){return"Iamreturning:"+accessorDescriptor;}, set:function(val){accessorDescriptor=val;}, configurable:true } }); child.accessorDescriptor='YUPENG'; console.log(child.accessorDescriptor); varCar2=function(){ this.name='aaaaaa' }//thisisanemptyobject,like{} Car2.prototype={ getInfo:function(){ return'A'+this.color+''+this.desc+'.'; } }; varnewCar=newCar2(); varcar2=Object.create(newCar,{ //valueproperties color:{writable:true,configurable:true,value:'red'}, //concretedescvalue rawDesc:{writable:true,configurable:true,value:'Porscheboxter'}, //dataproperties(assignedusinggettersandsetters) desc:{ configurable:true, get:function(){returnthis.rawDesc.toUpperCase();}, set:function(value){this.rawDesc=value.toLowerCase();} } }); car2.color='blue'; console.log(car2.getInfo()); car2.desc="XXXXXXXX"; console.log(car2.getInfo()); console.log(car2.name); </script> </body> </html>
结果为:
100
yupeng
yupeng1
201
Iamreturning:YUPENG
AbluePORSCHEBOXTER.
AblueXXXXXXXX.
aaaaaa
以上就是针对javascript一种新的对象创建方式Object.create()的详细介绍,希望对大家的学习有所帮助。