第3章 對象基礎
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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>
最後更新:2017-04-03 18:51:44