Javascript闭包模拟私有成员

通过闭包可以使得外部原型方法无法访问到内部的成员。如下例所示,原型方法返回的是undefined,这是因为闭包存在于Immutable中,导致无法访问到getWidth和getHeight。

function ImmutableRectangle(w,h){
    this.getWidth = function () { return w; }  ;
    this.getHeight = function () { return h; }  ;
}

 ImmutableRectangle.prototype.area = function(){
    return this.getWidth()*this.getHeight();
 }

alert(ImmutableRectangle(2,5)); // undefined
成员变量只能在函数内部使用,从而模拟实现了js的私有成员

function ImmutableRectangle(w,h){
    this.getWidth = function () { return w; }  ;
    this.getHeight = function () { return h; }  ;

  alert(this.getWidth()*this.getHeight()) ;
}

ImmutableRectangle(2,5);// 10

参考文章:

http://www.crockford.com/javascript/private.html

http://jibbering.com/faq/notes/closures/

http://www.codeproject.com/Articles/133118/Safe-Factory-Pattern-Private-instance-state-in-Jav

原文地址:https://www.cnblogs.com/yingzi/p/2582884.html