Pro javascript学习笔记之静态成员和属性
2008-09-18 15:37 wlstyle 阅读(485) 评论(0) 收藏 举报静态方法和属性
大多数方法和属性与类的示例结合。而静态成员和类本身结合。另外一种说法是静态成员是类级别的而不是实例级别。每一个静态成员只有一个copy.
var Car=(function(){2

3
//private static Attributes4

5
var numofCar=0;6

7
//private static methods8

9
function checkCarDoor(doors){10

11
if(typeof(doors) !='number'){12

13
throw new Error('the type of doors is increat');14

15
return false;16

17
}else{18

19
return true;20

21
}22

23
}24

25
return function(sColor,iDoors,sBrand){26

27
//private attributes28

29
var _sColor,_iDoors,_sBrand;30

31
//privileged methods32

33
this.getColor=function(){34

35
return _sColor;36

37
};38

39
this.setColor=function(sColor){40

41
_sColor= sColor;42

43
};44

45
this.getDoors= function(){46

47
return _iDoors;48

49
};50

51
this.setDoors= function(iDoors){52

53
checkCarDoor(iDoors);54

55
_iDoors= iDoors;56

57
};58

59
this.getBrand=function(){60

61
return _sBrand;62

63
};64

65
this.setBrand=function(sBrand){66

67
_sBrand= sBrand;68

69
};70

71
//constructor code72

73
numofCar++;74

75
if( numofCar>2){76

77
throw new Error('only two instance of car can created');78

79
80

81
}82

83
this.setColor(sColor);84

85
this.setDoors(iDoors);86

87
88

89
}90

91
92

93
})();94

95
//public static methods96

97
Car.sayHello= function(){98

99
alert('hello');100

101
}102

103
//public methods104

105
Car.prototype.showcar=function(){106

107
alert('the color is :'+this.getColor());108

109
}110

111

112
Car.sayHello();113

114
var onecar= new Car('red',5,'sexgirl');115

116
onecar.showcar();117

118
var twocar=new Car('black',6,'hotgirl');119

120
twocar.showcar();121

122

outline:

在构造函数中依旧定义了私有属性和私有方法。但是构造器从一个普通的函数变为一个嵌套的函数。该函数返回给Car这个变量。这样就可以创建一个闭包 这样就可以定义私有静态成员。函数后的双括号非常重要,这样使javascript代码加载是时候就执行该函数(早于调用构造函数)。执行的结果是返回另外一个函数。这个函数是一个Car的构造器。当Car被实例化的时候。这个内部函数被调用。外部函数的作用是用来创建这个闭包。这样才可以才能使用私有静态成员(numberofCar).该示例中的checkCarDoor是一个静态方法。因为没有为每个实例创建一个独立的checkCarDoor版本。
这样做到好处是显然是静态成员只在内存中只有一个copy。实例化两个Car后。这时候的静态属性numofCar为2.原先赋值的时候为0.内存中的这个copy会随着实例化不断的变化。而不是实例化一个对象就创建一个该对象的这个属性的copy.通常当一个私有方法不访问实例的私有变量(在上面代码中代表_sColor,_iDoors,_sBrand)时可以设置该方法为私有静态方法。公共静态成员很容易被创建。他们的创建不和构造器相关联。比如上面的代码中的sayHello()方法。
在javascript中除了原始类型(undefined.null,boolean,number,string)其余的都是对象。这意味着函数也是对象。因为对象本质上是哈希表。所以你能在任何适合添加对象成员。以上是结果是函数可以拥有属性和对象方法就像其他对象一样。他们可以在需要时候被添加。
摘录一段原文:
Note In JavaScript, everything except for variables of the three primitive types is an object (and even those primitives are automatically wrapped by objects when needed). This means that functions are also objects. Since objects are essentially hash tables, you can add members at any time. The end result of this is
that functions can have attributes and methods just like any other object, and they can be added whenever you want.


浙公网安备 33010602011771号