当前位置: 代码迷 >> Web前端 >> 种和原型的关系
  详细解决方案

种和原型的关系

热度:330   发布时间:2012-11-22 00:16:41.0
类和原型的关系
//类和原型的关系:类的所有实例对象都从同一个原型对象上继承属性
	
	//创建一个新对象
	function inherit(o)
	{
		if( o == null) return null;
		var t = typeof o;
		if(t !== "object" &&  t !== "function") return ;
		function f(){}
		f.prototype = o;
		return new f();
	}
	//这是一个工厂方法,返回一个新对象
	function range(from , to)
	{
		var r = inherit(range.methods);	
		r.from = from;
		r.to = to;
		return r;
	}
	//是range的内部方法,也就是原型对象定义的方法
	range.methods={
		includes:function(x)
		{
		  return this.from <=x && x<=this.to;
		},
		foreach:function(f){
			for(var x = Math.ceil(this.from); x<=this.to; x++) f(x);	
		}
	}
	
	var r = range(1,3);
	var is = r.includes(2);
 
 
	alert(al.from);

?

  相关解决方案