这里重拾简单主义,以一个最简单的例子把oo javascript说明白。
1.一个颇为精简的例子
只需理解三个关键字:
第一个是function ,js世界里class的定义用"function",function里面的内容就是构造函数的内容。
第二个是this指针,代表调用这个函数的对象。
第三个是prototype,用它来定义成员函数, 比较规范和保险。
//定义circle类,拥有成员变量r,常量pi和计算面积的成员函数area()
function circle(radius)
{
this.r = radius;
}
circle.pi = 3.14159;circle.prototype.area = function( ) {return circle.pi * this.r * this.r;}
//使用circle类var
c = new circle(1.0);
alert(c.area());
另外成员函数定义还可以写成这样:
function compute_area(){return circle.pi * this.r * this.r;}circle.prototype.area=compute_area;
2.继承
注意两点
1.定义继承关系 childcircle.prototype=new circle(0); 其中0是占位用的
2.调用父类的构造函数
this.base=circle;
this.base(radius);
//定义childcircle子类
function childcircle(radius)
{
this.base=circle;
this.base(radius);
}
childcircle.prototype=new circle(0);
function circle_max(a,b)
{
if (a.r > b.r) return a;
else return b;
}
childcircle.max = circle_max;
//使用childcircle子类
var c = new childcircle(1);
var d = new childcircle(2);
var bigger = d.max(c,d);
alert(bigger.area());
3.var式定义
js还支持一种var circle={raidus:1.0,pi:3.1415}的形式,语法就如css的定义。
因此如果circle只有一个实例,下面的定义方式更简洁:
var newcircle=
{
r:1.0,
pi:3.1415,
area: function(){ return this.pi * this.r * this.r;}
};
alert(newcircle.area());
闽公网安备 35060202000074号