【javascript基础】之【ecmascript5新特性】之Object.create

方法定义:用原型对象及属性的方式来新建一个对象。

语法

Object.create(proto [, propertiesObject ])


参数说明:

proto :  该参数所传入的对象将会成为新对象的原型。

propertiesObject : 类似这样的值,
{
    age : {
        value : 26
    },
    name : {
        value : "sunlaohu"
    }
}

 注意点:

如果proto参数传入的不是null或object,则会抛出 TypeError 错误

 demo:

var o;
 
// 创建一个原型为null的对象
o = Object.create(null);
 
 
o = {};
// 上行代码相当于:
o = Object.create(Object.prototype);
 
 
function Constructor(){}
o = new Constructor();
// 相当于:
o = Object.create(Constructor.prototype);
// 当然,就算Constructor方法有可运行的代码,Object.create也不会映射它。
 
 
//创建一个新对象,原型对象是空元素
//
添加单属性p.value=42
 
o = Object.create({}, { p: { value: 42 } })
 
//这样传进来的属性默认是不可写、不可枚举和不可删除的:
 
o.p = 24
o.p
//42
 
o.q = 12
for (var prop in o) {
   console.log(prop)
}
//"q"
 
delete o.p
//false
 
//指定ES3属性后就可以了
 
o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });

 兼容性:

 

兼容浏览器的解决代码:

Object.create && Object.create = function(proto){
  if(arguments.length > 1){
      throw new Error("[Object.create]暂不支持第二个属性参数!");
  }
  function Func(){};
  Func.prototype = proto;
  return new Func();
};

 参考文档:

 https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain#.E4.BD.BF.E7.94.A8Object.create.E5.88.9B.E5.BB.BA.E5.AF.B9.E8.B1.A1

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/create 

http://hax.iteye.com/blog/1146699 

 http://blog.csdn.net/kabukon/article/details/6913381

 http://blog.csdn.net/shyleoking/article/details/7316174

原文地址:https://www.cnblogs.com/sniper007/p/2767255.html