在 js中,类的实现是通过原型的继承机制。
通常的方法,是定义构造函数,即是定义类,类名即构造函数名,首字母必须大写。在其中定义一些共有的属性名。
同时,使用关键字prototype来定义构造函数的原型对象,在其中定义共享的方法。当定义好这些之后,必须通过关键字new来调用
构造函数,实现创建实例。此实例‘继承’所有原型的方法。
构造函数及原型对象实现类
这里使用犀牛书的示例 9-2 以及略微调整
1)构造函数
function Range(from,to){
this.from=from;
this.to=to;
}
2)原型对象
2.1)定义原型对象
Range.prototype={
//注意,Range.prototype={},这种形式重写了预定义的Range.prototype对象,去掉了constructor属性,因此我们需要显示给原型添加一个构造函数;
constructor:Range,//必写!!
//如果x在范围内,则返回true, 否则返回false
includes:function(x){
return this.from<=x && x<=this.to;
},
//这个函数内的每个整数都调用一次f
foreach:function(f){
for(var x=Math.ceil(this.from);x<this.to;x++) f(x);
},
//返回这个范围的字符串
toString:function(){
return "("+this.from+"..."+this.to+')';
}
}
2.2)由于预定义的原型对象Range.prototype本身就包含constructor属性,我们可以使用预定义的原型对象,然后依次添加方法
Range.prototype.includes=...
Range.prototype.foreach=...
Range.prototype.toString=...
3)实例化对象
var r=new Range(10,15);
4)调用共享方法
console.log(r.includes(2));//false
r.foreach(console.log);//10 11 12 13 14 15
console.log(r.toString())// (10...15)
es6写法
在es6中,可以使用class关键字,使其在写法上更加的清晰,将上述的例子改写如下; 这种只是在写法上做了修改,构造函数仍旧是Range1,方法仍旧加在Range1.prototype之上
class Range1{
constructor(from,to){
this.from=from;
this.to=to;
}
includes(x){//这是类的一个方法,不要加上function
return this.from<=x && x<=this.to;
}
foreach(f){
for(var x=Math.ceil(this.from);x<this.to;x++) f(x);
}
toString(){
return "("+this.from+"..."+this.to+')';
}
}
var r_new=new Range1(3,8);
console.log(r_new.includes(4));//true
r_new.foreach(console.log);
console.log(r_new.toString());//(3...8)