<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>定义类和对象</title>
</head>
<body>
1.工厂方式:<br />
<script type="text/javascript">
//定义
function createCar(color, doors, mpg) {
var oCar = new Object();
oCar.color = color;
oCar.doors = doors;
oCar.mpg = mpg;
oCar.showColor = function () { alert("1.工厂方式:" + this.color); };
return oCar;
}
//调用
var car = createCar("red", 4, 23);
car.showColor();
</script>
2.构造函数方式:<br />
<script type="text/javascript">
//定义
function Car(color, doors, mpg) {
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.showColor = function () { alert("2.构造函数方式:" + this.color); };
}
//调用
var car2 = new Car("blue", 4, 23);
car2.showColor();
</script>
3.原型方式:<br />
<script type="text/javascript">
//定义
function pCar() { }
pCar.prototype.color = "green";
pCar.prototype.doors = 4;
pCar.prototype.mpg = 23;
pCar.prototype.showColor = function () { alert("3.原型方式测试:" + this.color); };
//调用
var car3 = new pCar();
alert(car3 instanceof pCar); //允许用instanceof运算符检查给定变量指向的对象的类型。
car3.showColor();
</script>
4.混合构造函数/原型方式:<br />
<script type="text/javascript">
//定义
//构造函数定义属性
function sCar(color, doors, mpg) {
this.color = color;
this.doors = doors;
this.mpg = mpg;
}
//原型方式定义函数
sCar.prototype.showColor = function () { alert("4.混合构造函数/原型方式测试:" + this.color); };
//调用
var car4 = new sCar("yellow", 4, 23);
car4.showColor();
</script>
5.动态原型方式:<br />
<script type="text/javascript">
//定义
function dCar(color, doors, mpg) {
this.color = color;
this.doors = doors;
this.mpg = mpg;
//将对象的方法放到对象内部,更符合面向对象思想
if (typeof dCar._initialized == "undefined") {
dCar.prototype.showColor = function () { alert("5.动态原型方式测试:" + this.color); };
dCar._initialized = true;
}
}
//调用
var car5 = new dCar("black", 4, 23);
car5.showColor();
</script>
</body>
</html>