JavaScript權威指南學習之路---基礎、對象

 

 1.經過繼承(Object.create())建立對象的好處?
防止函數庫無心間或惡意的修改那些不受你控制的對象。不是將對象直接傳入到函數,而是將它的繼承對象傳入,
函數讀取到的其實是繼承來的值,若是給繼承對象賦值,則影響到的是繼承的對象,而不是當前對象自己。dom

 1 var o = {};
 2 o.x = 1;
 3 var p = inherit(o);
 4 p.y = 2;
 5 var q = inherit(p);
 6 q.z = 3;
 7 var s = q.toString();    //3 x爲o的屬性,y爲p的屬性,z纔是q的屬性
 8 q.x + q.y
 9 
10 function inherit(p) {
11   if(p == null) throw TypeError();
12   if(Object.create) return Object.create(p);
13   var t = typeof p;
14   if(t !== "objcet" && t !== "function") throw TypeError();
15   function f() {};
16   f.prototype = p;
17   return new f();
18   
19 }

 2.如何防止查詢屬性報錯函數

1 var len = book.subtitle.length; //null 和 undefined都沒有屬性,報錯
2 //冗餘但很易懂的方法
3 var len = undifined;
4 if(book) {
5     if(book.subtitle) len = book.subtitle.length;
6 }
7 //一種更簡練的經常使用方法。
8 var len = book && book.subtitle && book.subtitle.length;

 3.檢測屬性的三種方法this

1)in
var o = {x: 1};
"x" in o;    //true
2)hasOwnProperty()
o.hasOwnproperty("x") //true 有一個自有屬性,繼承而來的不算
3)propertyIsEnumerable()    //hasOwnProperty的加強版
o.hasOwnProperty("x")    //true 有一個自有屬性且是可枚舉的spa

4.存取器屬性prototype

 1 var p = {    //存取器屬性,注意寫法,函數後是逗號分隔,get、set與函數名之間沒有冒號
 2   x : 1,
 3   y : 2,
 4   
 5   get r() {return Math.sqrt(this.x * this.x + this.y * this.y); },
 6   set r(newValue) {
 7     var oldValue = Math.sqrt(this.x * this.x + this.y * this.y);
 8     var ratio = newValue / oldValue;
 9     this.x *= ratio;
10     this.y *= ratio;
11   },
12   //只讀存取器屬性,只有get方法
13   get theta() { return Math.atan2(this.y, this.x); },
14 }

5.屬性的特性
通常的屬性都有四個特性:value, writable, enumerable, configurable
Object.getOwnPropertyDescriptor({x:1}, "x"); //1, true, true, true
該方法能夠得到特定屬性的屬性描述符。
Object.getOwnPropertyDescriptor(random, "obct"); //get:/*func*/, set:undefined, enumerable:true, configurable:true;code

Object.defineProperty(
    Object,
    "Object.value", 
    {
         value:arg0, 
         writable: arg1,
         enumerable: arg2,
         configurable: arg3
    })

能夠設置屬性的特性。同時建立或修改多個屬性對象

var p = Object.defineProperties({}, {
  x: {
    value: 1,
    writable: true,
    enumerable: true,
    configurable: true
  },
   y: {
    value: 1,
    writable: true,
    enumerable: true,
    configurable: true
  },
  r: {
    get: function () {
      return Math.sqrt(this.x * this.x + this.y * this.y);
    },
    enumerable: true,
    configurable: true
  }
})
相關文章
相關標籤/搜索