如何利用JS创建自定义的类和对象?
1. 工厂的方式
<script language="JavaScript"> function createCar(color, mpg) { var car = new Object(); car.color = color; car.mpg = mpg; car.showCar = function () { alert(this.color); alert(this.mpg); }; return car; } var car = createCar("red", 23); car.showCar(); </script> |
以上方法:每次createCar都要创建新函数showCar,每个对象都有自己的showCar,实际上每个对象可以共享showCar函数
<script language="JavaScript"> function createCar(color, mpg) { var car = new Object(); car.color = color; car.mpg = mpg; car.showCar = showCar; return car; } function showCar() { alert(""); alert(this.color); alert(this.mpg); } var car = createCar("red", 23); car.showCar(); </script> |
以上方法:解决了重复创建函数问题,但是这个函数不像是对象特有的方法
2. 构造函数方法
<script language="JavaScript"> function Car(color, mpg) { this.color = color; this.mpg = mpg; this.showCar = showCar; } function showCar() { alert("Car"); alert(this.color); alert(this.mpg); } var car = new Car("red", 23); car.showCar(); </script> |
以上方法:和工厂方法一样,都会产生重复定义函数,以及函数不像是对象特有的方法的问题
3. 混合构造函数/原型方法
<script language="JavaScript"> function Car(color, mpg) { this.color = color; this.mpg = mpg; } Car.prototype.setColor = function (color) { this.color = color } Car.prototype.showCar = function () { alert("prototype"); alert(this.color); alert(this.mpg); } var car = new Car("red", 23); car.showCar(); car.setColor("blue"); car.showCar(); </script> |
以上方法:利用对象的prototype属性,将所有属性和方法直接赋予对象的prototype属性,每个Car实例存放的都是指向showColor函数的指针。
4. 动态原型方法
<script language="JavaScript"> function Car(color, mpg) { this.color = color; this.mpg = mpg;
if ((typeof Car._initialized) == "undefined") { Car.prototype.showCar = function () { alert("prototype"); alert(this.color); alert(this.mpg); }; Car._initialized = true; } } var car = new Car("red", 23); car.showCar(); </script> |
以上方法:利用_initialized做标志位,来判断是否给原型赋予了任何方法