function Complex(real, imaginary) { this.x = real; // The real part of the number this.y = imaginary; // The imaginary part of the number } ; Complex.prototype.magnitude = function( ) { return Math.sqrt(this.x*this.x + this.y*this.y); }; Complex.prototype.negative = function( ) { return new Complex(-this.x, -this.y); }; Complex.prototype.add = function(that) { return new Complex(this.x + that.x, this.y + that.y); } ; Complex.prototype.multiply = function(that) { return new Complex(this.x * that.x - this.y * that.y, this.x * that.y + this.y * that.x); }; Complex.prototype.toString = function( ) { return "{" + this.x + "," + this.y + "}"; }; Complex.prototype.equals = function(that) { return this.x == that.x && this.y == that.y; } ; Complex.prototype.valueOf = function( ) { return this.x; }; Complex.sum = function (a, b) { return new Complex(a.x + b.x, a.y + b.y); }; Complex.product = function(a, b) { return new Complex(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); }; Complex.ZERO = new Complex(0,0); Complex.ONE = new Complex(1,0); Complex.I = new Complex(0,1);
这个例子实现了不可变的Rectangule对象。长宽不能变。只能通过方法访问。
function ImmutableRectangle(w, h) { // This constructor does not store the width and height properties // in the object it initializes. Instead, it simply defines // accessor methods in the object. These methods are closures and // the width and height values are captured in their scope chains. this.getWidth = function() { return w;} this.getHeight = function() { return h;} } ImmutableRectangle.prototype.area = function() { return this.getWidth() * this.getHeight(); }; var r=new ImmutableRectangle(3,4); r.getWidth();