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()同样