js权威指南9-1例子:实例属性、实例方法、类属性、类方法

// We begin with the constructor
function 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);      // 创建一个Circle类的实例
c.r = 2.2;                    // 设置r的实例属性         Set the r instance property
var a = c.area();             // 调用实例方法 area()   Invoke the area() instance method
var x = Math.exp(Circle.PI);  // 使用类属性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); // 使用实例方法 max()    Use the max() class method
posted on 2012-07-27 15:11  rorodo  阅读(288)  评论(0)    收藏  举报