JavaScript的模拟类

构造函数和原型对象,用它们来创建表示圆的对象。
Circle类
//begin with the constructor
//构造函数
fuction Circle(radius){
//r is an instance property,defined and initialized in the constructor
//实例属性
this.r = radius;
}

//Circle.PI is a class property--it is a property of the constructor function.
//类属性
Circle.PI = 3.14159;

//Here is an instance method that computes a circle's area.
//实例方法
Circle.prototype.area = function(){ return Circle.PI*this.r*this.r;}

//This class method takes two Circle objects and returns the one that has the larger radius.
//类方法
Circle.max = function(a,b){
if(a.r>b.r) return a;
else return b;
}

//Here is some code that uses each of these fields;
var c = new Circle(1.0); //Create an instance of the Circle class
//创建一个圆类实例
c.r = 2.2; //Set the r instance proterty
//设置一个实例属性
var a = c.area(); //Invoke the area() instance method
//引入实例方法
var x = Math.exp(Circle.PI) //Use the PI class property in our own computation
//类属性
var d = new Circle(1.2) //Create another Circle instance
//创建另一个圆类
var bigger = Circle.max(c,d)//Use the max() class method
//类方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值