類和原型之工廠模式!

 1 function inherit(p){
 2          if(p == null) throw TypeError();//非空對象不然拋出異常
 3          if(Object.creat){
 4              //經過Object.creat()建立繼承了其屬性和方法
 5             return Object.creat(p);//若是存在Object.creat 直接使用這個對象
 6          }
 7          var t = typeof p;//不然進一步的檢測
 8          if(t !== "object" && t !== "function") throw TypeError()
 9          function f(){};
10          f.prototype = p;//p對象賦值給f的原型,這時f原型指向就是p的原型
11          return  new f();//返回實例對象
12       }
13       /*工廠方法
14        *主要功能:建立範圍對象
15        */
16       function range(from,to){
17          var r =inherit(range.methods);
18          //初始化
19          r.from = from;
20          r.to = to;
21          return r;//返回實例對象
22       }
23       //函數添加一個屬性,存儲一組行爲的方法
24       range.methods ={
25          includes : function (x){
26             return this.from <= x && x <= this.to;
27          },
28          foreach : function(f){
29              for(var x = Math.ceil(this.from);x <= this.to; x++) f(x);
30          },
31          toString : function(){return "("+this.from+"...."+this.to+")";}
32       };
33       var r = range(1,3);
34       r.includes(2);
35       r.foreach(console.log);
36       console.log(r);

關於Object.creat();函數

建立一個新對象,第一個參數是這個對象的原型,第二個參數是可選的。this

是個靜態函數,而不是提供給某個對象調用的方法,只須要傳入對象的原型。spa

例如1:  var o1 = Object.create({x:1,y:2});//繼承了屬性x和y prototype

若是傳入是null 則沒有繼承任何對象,甚至不包括基礎的方法,好比toString(),它也不能和 「+」運算符一塊兒工做。code

例如2:對象

var o2 = Object.create(null);//不繼承任何屬性和方法

若是想建立普通的空對象blog

能夠經過: {} 和 new Object()建立對象 傳入 Object.prototype繼承

var o3 = Object.create(Object.prototype);//和{}、new Object()同樣
相關文章
相關標籤/搜索