类属性和方法,对象属性和方法。以及用闭包做的私有属性例子。

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();

转载于:https://www.cnblogs.com/rorodo/archive/2012/07/17/2595353.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值