日期:2014-05-16  浏览次数:20312 次

JavaScript类
JavaScript类
类让每个对象都共享某些属性,这种“共享”的特征是非常有用的。

类和原型:在JavaScript中,类的所有实例对象都从同一个原型对象上继承属性[原型对象是类的核心]。
function range(from, to){   //编写的js代码
	var r = inherit(range.methods);
	r.from = from;
	r.to = to;
	return r;
}
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);
		},
		
		toString : function() {return "(" + this.from+ "..." +this.to+ ")";}
};
inherit = function(p){ //对象原型方法range.methods
	if(p==null) throw TypeError();
	if(Object.create)Object.create(p);
	var t = typeof p;
	if(t != "function" && t!= "object") throw TypeError();
	function f(){};
	f.prototype = p;
	return new f();
};
将上述js代码文件引入到页面中,在页面中编写的代码如下:
var r = range(1,3);            //初始化函数
console.log(r.includes(2));   //true
r.foreach(console.log);		 //1 2 3
console.log(r);             //(1...3)


类和构造函数:以上方法在正常开发中不常用,毕竟他没有构造函数,构造函数是用来初始化新创建的对象,如下例子:
function Range(from,to){  //构造函数
	this.from = from;
	this.to = to;
}
Range.prototype = {      //新对象的原型
	
		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);
		},
		
		toString: function(){
			return "("+ this.from +"..." +this.to +")";
		}
};

将上述js代码文件引入到页面中,在页面中编写的代码如下:
var r = new Range(1,3);     //通过构造函数创建对象
console.log(r.includes(2));  //true
r.foreach(console.log);//123
console.log(r);        //(1...3)

注意:开发者可以通过命名约定来(构造函数的首字母大写,普通方法首字母小写)判断是否应当在函数之前加关键字new

构造函数属性:
从上面的例子中,我们通过Range.prototype定义为一个新对象,这个对象包含类所需的方法。其实没有必要新创建一个对象,用单个对象直接量的属性就可以方便地定义原型善过的方法。
任何javaScript函数都可以用作构造函数,并且调用构造函数是需要用到一个prototype属性的。每个函数都拥有一个prototype属性。这个属性的值是一个对象,如下例子:
var F = function(){};	//一个函数对象
var p = F.prototype;	//与F相关联的原型对象
var c = p.constructor;	//与原型先关联的函数
console.log(c===F);		//true 对于任意函数F.prototype.constructor==F

注意:预定义的原型对象包含constructor属性,如下例子[简化以上Range例子]:

function defineClass(constructor,methods,statics){    //define.js
	if(methods) extend (constructor.prototype, methods);
	if(statics) extend (constructor, statics);
	return constructor;
}

function extend(o,p){
	for(prop in p){
		o[prop] = p[prop];
	}
	return o;
}
var SimpleRange =  defineClass(   //SimpleRange.js
		function(f,t) {this.f = f; this.t = t;},
		{
		includes: function(x) {return this.f <= x && x <= this.t;},
		toString: function() {return "("+this.f+"..."+this.t+")";}
		},
		
		{upto:function(t) {return new SimpleRange(1,t);}});
	var s = new SimpleRange(0,4); //在HTML中的执行方法(再次创建对象)[要引入上面两个js文件]  	
                                      //方法1:var s = SimpleRange.upto(3);