標籤:console enum evel www conf object_c 詳細 doc 例子
原文地址:http://www.cnblogs.com/yupeng/p/3478069.html
1.Object.create() 是什嗎?
Object.create(proto [, propertiesObject ]) 是E5中提出的一種新的對象建立方式,第一個參數是要繼承的原型,如果不是一個子函數,可以傳一個null,第二個參數是對象的屬性描述符,這個參數是可選的。
例如:
1 function Car (desc) { 2 this.desc = desc; 3 this.color = "red"; 4 } 5 6 Car.prototype = { 7 getInfo: function() { 8 return ‘A ‘ + this.color + ‘ ‘ + this.desc + ‘.‘; 9 }10 };11 //instantiate object using the constructor function12 var car = Object.create(Car.prototype);13 car.color = "blue";14 alert(car.getInfo());
結果為:A blue undefined.
2.propertiesObject 參數的詳細解釋:(預設都為false)
資料屬性
- writable:是否可任意寫
- configurable:是否能夠刪除,是否能夠被修改
- enumerable:是否能用 for in 枚舉
- value:值
訪問屬性:
3.例子:直接看例子就知道怎麼用。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>yupeng‘s document </title> 5 <meta charset="utf-8"/> 6 </head> 7 <body> 8 <script type="text/javascript"> 9 10 var obj = {11 12 a:function(){13 console.log(100)14 },15 b:function(){16 console.log(200)17 },18 c:function(){19 console.log(300)20 }21 22 }23 24 var newObj = {};25 26 newObj = Object.create(obj,{27 t1:{28 value:‘yupeng‘,29 writable:true30 },31 bar: {32 configurable: false,33 get: function() { return bar; },34 set: function(value) { bar=value }35 }36 37 })38 39 console.log(newObj.a());40 console.log(newObj.t1);41 newObj.t1=‘yupeng1‘42 console.log(newObj.t1);43 newObj.bar=201;44 console.log(newObj.bar)45 46 function Parent() { }47 var parent = new Parent();48 var child = Object.create(parent, {49 dataDescriptor: {50 value: "This property uses this string as its value.",51 writable: true,52 enumerable: true53 },54 accessorDescriptor: {55 get: function () { return "I am returning: " + accessorDescriptor; },56 set: function (val) { accessorDescriptor = val; },57 configurable: true58 }59 });60 61 child.accessorDescriptor = ‘YUPENG‘;62 console.log(child.accessorDescriptor);63 64 65 66 var Car2 = function(){67 this.name = ‘aaaaaa‘68 } //this is an empty object, like {}69 Car2.prototype = {70 getInfo: function() {71 return ‘A ‘ + this.color + ‘ ‘ + this.desc + ‘.‘;72 }73 };74 75 var newCar = new Car2();76 77 var car2 = Object.create(newCar, {78 //value properties79 color: { writable: true, configurable:true, value: ‘red‘ },80 //concrete desc value81 rawDesc: { writable: true, configurable:true, value: ‘Porsche boxter‘ },82 // data properties (assigned using getters and setters)83 desc: { 84 configurable:true, 85 get: function () { return this.rawDesc.toUpperCase(); },86 set: function (value) { this.rawDesc = value.toLowerCase(); } 87 }88 }); 89 car2.color = ‘blue‘;90 console.log(car2.getInfo());91 car2.desc = "XXXXXXXX";92 console.log(car2.getInfo());93 console.log(car2.name);94 95 96 97 </script>98 </body>99 </html>
結果為:
100yupeng
yupeng1
201
I am returning: YUPENG
A blue PORSCHE BOXTER.
A blue XXXXXXXX.
aaaaaa
javascript一種新的對象建立方式-Object.create()