
Code
1 var Car=function(sColor,iDoors){
2
3 //private attribution
4
5 var color,doors;
6
7 //private methods
8
9 function checkDoors(doors){
10
11 if( typeof(doors)!= 'number'){
12
13 throw new Error('type of doors is incorret!');
14
15 return false;
16
17 }else {
18
19 return true;
20
21 }
22
23
24
25 }
26
27 //privileged methods
28
29 this.getColor= function(){
30
31 return color;
32
33 };
34
35 this.setColor=function(sColor){
36
37 color=sColor;
38
39 };
40
41 this.getDoors=function(){
42
43 return doors;
44
45 };
46
47 this.setDoors=function(iDoors){
48
49 checkDoors(iDoors);
50
51 doors= iDoors;
52
53 };
54
55 //constructor code
56
57 this .setColor( sColor);
58
59 this .setDoors( iDoors);
60
61 }
62
63 //public methods
64
65 Car.prototype.ShowCar= function(){
66
67 alert("the car's color is: "+ this.getColor()+" the car's doors is: "+ this.getDoors());
68
69 }
70
71 var fordCar= new Car('blue',4);
72
73 fordCar.ShowCar();
74
75
由于javascript是依据function来限定变量的作用域,外部无法直接使用函数内部定义的变量。例如你无法在函数外部直接alert(doors),会提示doors 未被定义。

可以看到我们在Car 函数中定义了两个变量 color和doors这两个变量 ,由于在函数内部,所以外部无法调用这两个变量。这就成了真正意义上的私有变量。
在这里还有一个特权方法(Priviledge methods)。

这些特权方法以this关键字标记 这样就可以外部访问。从而成为一个公共的方法。又因为这些方法在构造函数的作用域中所以可以访问私有变量。
在这种模式中每一次实例化都会创建这些特权方法和私有方法的副本。如果实例化了很多对象 这样无疑会占用较多的内存。还有一个问题是以这种模式设计难以进行继承。因为要继承意味着。属性和方法是公用的。也就是public的。而这种模式属性是私有的。子类无法访问超类的属性。