// Define a constructor method for our class. // Use it to initialize properties that will be different for // each individual Circle object. function Circle(x, y, r) { this.x = x; // The X-coordinate of the center of the circle this.y = y; // The Y-coordinate of the center of the circle this.r = r; // The radius of the circle } // Create and discard an initial Circle object. // This forces the prototype object to be created in JavaScript 1.1. new Circle(0,0,0); // Define a constant: a property that will be shared by // all circle objects. Actually, we could just use Math.PI, // but we do it this way for the sake of instruction. Circle.prototype.pi =3.14159; // Define a method to compute the circumference of the circle. // First declare a function, then assign it to a prototype property. // Note the use of the constant defined above. function Circle_circumference( ) { return2*this.pi *this.r; } Circle.prototype.circumference = Circle_circumference; // Define another method. This time we use a function literal to define // the function and assign it to a prototype property all in one step. Circle.prototype.area =function( ) { returnthis.pi *this.r *this.r; } // The Circle class is defined. // Now we can create an instance and invoke its methods. var c =new Circle(0.0, 0.0, 1.0); var a = c.area( ); var p = c.circumference( );
内置的类的 prototype.
不光是用户自定义的类可以有 prototype. 系统内置的类比如 String, Date 也都有的。而且你可以向他们添加新的方法,属性等。 下面这段代码就对所有的 String 对象添加了一个有用的函数:
// Returns true if the last character is c String.prototype.endsWith =function(c) { return (c ==this.charAt(this.length-1)) }