3.原型方式
Code
1 <script language="javascript" type="text/javascript">
2 function car(){
3 }
4 car.prototype.color="red";
5 car.prototype.doors=4;
6 car.prototype.mpg=23;
7 car.prototype.showcolor=function(){
8 alert(this.color);
9 };
10 var car1=new car();
11 var car2=new car();
12 </script>
13
首先,这个构造函数没有参数,其次,在属性指向的是对象,而不是函数的时。函数的共享不会造成任何问题,但对象却很少是被多个实例共享的。
Code
1 <script type="text/javascript">
2 function Car() {
3 }
4 Car.prototype.color = "red";
5 Car.prototype.doors = 4;
6 Car.prototype.mpg = 23;
7 Car.prototype.drivers = new Array("Mike", "Sue");
8 Car.prototype.showColor = function () {
9 alert(this.color);
10 };
11 var oCar1 = new Car();
12 var oCar2 = new Car();
13 oCar1.drivers.push("Matt");
14 alert(oCar1.drivers); //outputs "Mike,Sue,Matt"
15 alert(oCar2.drivers); //outputs "Mike,Sue,Matt"
16 </script>
17
4.混合的构造函数/原型方式
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.drivers = new Array("Mike", "Sue");
7 }
8
9 Car.prototype.showColor = function () {
10 alert(this.color);
11 };
12
13 var oCar1 = new Car("red", 4, 23);
14 var oCar2 = new Car("blue", 3, 25);
15
16 oCar1.drivers.push("Matt");
17
18 alert(oCar1.drivers); //outputs "Mike,Sue,Matt"
19 alert(oCar2.drivers); //outputs "Mike,Sue"
20
21
5.动态原型方法
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.drivers = new Array("Mike", "Sue");
7 if (typeof Car._initialized == "undefined") {
8 Car.prototype.showColor = function () {
9 alert(this.color);
10 };
11 Car._initialized = true;
12 }
13 }
14 var oCar1 = new Car("red", 4, 23);
15 var oCar2 = new Car("blue", 3, 25);
16 oCar1.drivers.push("Matt");
17 alert(oCar1.drivers); //outputs "Mike,Sue,Matt"
18 alert(oCar2.drivers); //outputs "Mike,Sue"
19 </script>
20
目前使用最广泛的是混合的构造函数/原型方式。此外,动态原型方法也很流行,在功能是上与混合的构造函数/原型方式等价。