javascript的创建对象object.create()和属性检测hasOwnPrototype()和propertyIsEnumerable()

Object.create("参数1[,参数2]")是E5中提出的一种新的对象的创建方式.
第一个参数是要继承到新对象原型上的对象;
第二个参数是对象属性.这个参数可选,默认为false
第二个参数的具体内容:
writable:是否可任意写, true可以,false不可以
configuration:是否能够删除,是否能够被修改.
enumerable:是否能用for in枚举
value:属性值
get()读
set()写

 1 Object.create=function(obj){
 2             var F=function(){};
 3             F.prototype=obj;
 4             return new F();
 5         };
 6       //再来一段代码演示参数的使用.
 7         function Parent(){}
 8         var p=new Parent();
 9         var newObj=Object.create(p,{
10             name:{
11                 value:"思思博士",//name值
12                 writable:true,//可写
13                 enumerable:false//不可枚举
14             },
15             age:{
16                 get:function(){return "我今年"+age+"岁";},//读取age
17                 set:function(val){age=val;},//设置age
18                 configuration:false//能否删除
19             }
20         });        
21         console.log("newobj的属性name:"+newObj.hasOwnProperty("name"));//false
22         console.log("parent的属性name:"+p.hasOwnProperty("name"));//false

上面一段代码是创建一个newObj对象,这个对象的原型是继承自parent
又有false可以推断出name是来自于原型中,并且不是来自于p这个对象.

 hasOwnProperty().方法用来检测给定的名字是否是对象的只有属性.对于继承属性它将返回false  

1  var o={x:1};
2         console.log(o.hasOwnProperty("x"));//true.
3         console.log(o.hasOwnProperty("y"));//false
4         console.log(o.hasOwnProperty("toString"));//false

propertyIsEnumerable()是hasOwnProperty()的增强版,只有检测到是只有属性且这个属性的可枚举为true是它才返回true.

1 var obj=Object.create(o);
2         obj.xx=1;
3         console.log(obj.propertyIsEnumerable("x"));//false
4         console.log(obj.propertyIsEnumerable("xx"));//true
5         console.log(Object.prototype.propertyIsEnumerable("toString"));//false
原文地址:https://www.cnblogs.com/guoyansi19900907/p/3730511.html