1. 工厂方式
1<script language="javascript" type="text/javascript">
2var car=new Object;
3car.color="red";
4car.doors=4;
5car.mpg=23;
6car.showcolor=function(){
7 alert(this.color)
8};
9</script>
10
执行了这行代码以后,就可以使用对象car,问题是可能需要创建多个car实例。要解决此问题,开发者创造了能创建并返回特定类型的对象的工厂函数(factory function)
Code
1<script language="javascript" type="text/javascript">
2function createcar(){
3var car=new Object;
4car.color="red";
5car.doors=4;
6car.mpg=23;
7car.showcolor=function(){
8 alert(this.color)
9};
10return car;
11}
12var car1=createcar();
13var car2=createcar();
14</script>
15
使用该方法,可以容易的创建car对象的两个版本,它们的属性完全一样,可以修改createcar函数,给它传递各个属性的默认值,而不是赋予属性默认值
Code
1<script type="text/javascript">
2function createCar(sColor, iDoors, iMpg) {
3 var oTempCar = new Object;
4 oTempCar.color = sColor;
5 oTempCar.doors = iDoors;
6 oTempCar.mpg = iMpg;
7 oTempCar.showColor = function () {
8 alert(this.color)
9 };
10 return oTempCar;
11}
12var oCar1 = createCar("red", 4, 23);
13var oCar2 = createCar("blue", 3, 25);
14oCar1.showColor(); //outputs "red"
15oCar2.showColor(); //outputs "blue"
16</script>
17
每次调用函数createcar,都要创建函数showcolor,意味着每个函数都有自己的showcolor版本,事实上,每个对象都共享了同一个函数
于是在工厂函数外定义对象方法,然后通过属性指向该方法。
Code
1 <script language="javascript" type="text/javascript">
2 function showColor(){
3 alert(this.color);
4 }
5
6 function createcar(sColor, iDoors, iMpg) {
7 var car=new Object;
8 car.color = sColor;
9 car.doors = iDoors;
10 car.mpg = iMpg;
11 car.showColor = showColor;
12 return car;
13 }
14
15 var oCar1 = new createcar("red", 4, 23);
16 var oCar2 = new createcar("blue", 3, 25);
17 oCar1.showColor(); //outputs "red"
18 oCar2.showColor(); //outputs "blue"
19 </script>
20
从功能上讲,这样解决了重复创建函数对象的问题,但该函数看起来不像对象的方法
2.构造函数方式
Code
1 <script type="text/javascript">
2 function Car(sColor, iDoors, iMpg) {
3 this.color = sColor;
4 this.doors = iDoors;
5 this.mpg = iMpg;
6 this.showColor = function () {
7 alert(this.color)
8 };
9 }
10
11 var oCar1 = new Car("red", 4, 23);
12 var oCar2 = new Car("blue", 3, 25);
13 oCar1.showColor(); //outputs "red"
14 oCar2.showColor(); //outputs "blue"
15 </script>
16