- javascript中模仿类
function Circle () {
}上面的代码就声明了一个类,准确说是一个对象构造器(constructor),这是一个空类,没有任何属性和方法,没有什么意义,我们可以添加需要的属性和方法。
- 属性和方法
function Circle (xPoint, yPoint, radius) {
this.x = xPoint; // The x component of the center of the circle.
this.y = yPoint; // The y component of the center of the circle.
this.r = radius; // The radius of the circle.
this.getArea()=function(){Math.PI*this.r*this.r;}; //return area of the circle.circle包含3个属性和一个方法,x,y表示坐标,r表示半径,getArea方法返回圆的面积。
- 实例化
var circle = new Circle(1,2,5);//instantiate a Circle object.
var circleArea = circle.getArea();//get the area of the circle;通过关键字来实例化一个类,对象点操作符来访问对象方法和属性。