一种新的javascript对象创建方式Object.create()

时间:2021-05-25

Object.create() 是什么?
Object.create(proto [, propertiesObject ]) 是E5中提出的一种新的对象创建方式,第一个参数是要继承的原型,如果不是一个子函数,可以传一个null,第二个参数是对象的属性描述符,这个参数是可选的。
例如: 

function Car (desc) { this.desc = desc; this.color = "red";} Car.prototype = { getInfo: function() { return 'A ' + this.color + ' ' + this.desc + '.'; }};//instantiate object using the constructor functionvar car = Object.create(Car.prototype);car.color = "blue";alert(car.getInfo());

结果为:A blue undefined.

1、propertiesObject 参数的详细解释:(默认都为false)
数据属性:

  • writable:是否可任意写
  • configurable:是否能够删除,是否能够被修改
  • enumerable:是否能用 for in 枚举
  • value:值

访问属性:

  • get(): 访问
  • set(): 设置

2、例子:直接看例子就知道怎么用。 

<!DOCTYPE html><html><head> <title>yupeng's document </title> <meta charset="utf-8"/></head><body> <script type="text/javascript"> var obj = { a:function(){ console.log(100) }, b:function(){ console.log(200) }, c:function(){ console.log(300) } } var newObj = {}; newObj = Object.create(obj,{ t1:{ value:'yupeng', writable:true }, bar: { configurable: false, get: function() { return bar; }, 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) function Parent() { } var parent = new Parent(); var child = Object.create(parent, { dataDescriptor: { value: "This property uses this string as its value.", writable: true, enumerable: true }, accessorDescriptor: { get: function () { return "I am returning: " + accessorDescriptor; }, set: function (val) { accessorDescriptor = val; }, configurable: true } }); child.accessorDescriptor = 'YUPENG'; console.log(child.accessorDescriptor); var Car2 = function(){ this.name = 'aaaaaa' } //this is an empty object, like {} Car2.prototype = { getInfo: function() { return 'A ' + this.color + ' ' + this.desc + '.'; } }; var newCar = new Car2(); var car2 = Object.create(newCar, { //value properties color: { writable: true, configurable:true, value: 'red' }, //concrete desc value rawDesc: { writable: true, configurable:true, value: 'Porsche boxter' }, // data properties (assigned using getters and setters) desc: { configurable:true, get: function () { return this.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
I am returning: YUPENG
A blue PORSCHE BOXTER.
A blue XXXXXXXX.
aaaaaa

以上就是针对javascript一种新的对象创建方式Object.create()的详细介绍,希望对大家的学习有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章