首页 > 其他 > 详细

Object.create()

时间:2017-11-29 14:20:23      阅读:215      评论:0      收藏:0      [点我收藏+]

1.Object.create()是什么?

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

例子:

function Car(desc){

this.desc = desc;

this.color = red;

}

Car.prototype.getInfo = function () {

return ( this.color +" "+ this.desc);

}

var car = Object.create(Car.prototype);

car.color = "blue";

console.log(car.getInfo());

输出结果:Ablue undefined

2.propertiesObject 参数的详细解释:(默认都为false)

数据属性

writable:是否可任意写

configurable:是否能够删除,是否能够被修改

enumerable:是否能用 for in 枚举

value:值

访问属性:

get():访问

set():设置

3.例子:直接看例子怎么用

var o;

// 创建一个原型为null的空对象
o = Object.create(null);


o = {};
// 以字面量方式创建的空对象就相当于:
o = Object.create(Object.prototype);


o = Object.create(Object.prototype, {
  // foo会成为所创建对象的数据属性
  foo: { 
    writable:true,
    configurable:true,
    value: "hello" 
  },
  // bar会成为所创建对象的访问器属性
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) {
      console.log("Setting `o.bar` to", value);
    }
  }
});


function Constructor(){}
o = new Constructor();
// 上面的一句就相当于:
o = Object.create(Constructor.prototype);
// 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码


// 创建一个以另一个空对象为原型,且拥有一个属性p的对象
o = Object.create({}, { p: { value: 42 } })

// 省略了的属性特性默认为false,所以属性p是不可写,不可枚举,不可配置的:
o.p = 24
o.p
//42

o.q = 12
for (var prop in o) {
   console.log(prop)
}
//"q"

delete o.p
//false

//创建一个可写的,可枚举的,可配置的属性p
o2 = Object.create({}, {
  p: {
    value: 42, 
    writable: true,
    enumerable: true,
    configurable: true 
  } 
});

 

Object.create()

原文:http://www.cnblogs.com/dasheng0217/p/7920097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!