摘要:HTML5 & JavaScript 程式開發實戰修練(5/5)
JavaScript嚴格來說並非物件導向程式;不過還是透過"模擬"的寫法來達到物件導向的精神
以下範例即可達到物件導向中其中的封裝(Encapsulation)及多型(Overloading) 精神:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script>
function Employee()
{
//屬性
this.ID = "001"
this.Name = "remhom"
this.Job = "顧問"
//模擬私有屬性(未加this關鍵字)
salary = "99000"
//****模擬「多型」寫法 Begin***
if (arguments.length == 4) {
this.ID = arguments[0];
this.Name = arguments[1];
this.Job = arguments[2];
salary = arguments[3];
}
//****模擬「多型」寫法 End***
//方法
this.showName = function () {
alert("員工編號:"+this.ID+" ; 員工名字:" + this.Name + " ; 職稱:" + this.Job);
};
this.raises = function (Money) {
salary = parseInt(salary) + parseInt(Money);
};
//模擬封裝;公開的方法;但需要密碼驗證
this.ShowSalary = function (password) {
if (password="123")
PShowSalary();
};
//模擬私有的方法(未加this關鍵字)
PShowSalary = function () {
alert("薪水:" + salary + "元");
};
}
var emp = new Employee(); //建立 Employee Class
alert(emp.Name); //==>remhom
emp.showName(); //==>員工編號:001 ; 員工名字:remhom ; 職稱:顧問
//emp.PShowSalary(); //***Error***
emp.ShowSalary(123); //==>薪水:99000
alert(emp.salary); //undefined
emp.salary = parseInt(emp.salary) + 1000; //***無作用***
emp.ShowSalary(123); //==>薪水:99000
emp.raises(1000); //***加薪1000***
emp.ShowSalary(123); //==>薪水:10000
//呼叫模擬「多型」Employee
var emp1 = new Employee("002", "Kiwi", "助理", "22000");
emp1.showName(); //==>員工編號:002 ; 員工名字:Kiwi ; 職稱:助理
emp.ShowSalary(123); //==>薪水:22000
emp.showName(); //==>員工編號:001 ; 員工名字:remhom ; 職稱:顧問
</script>
</head>
<body>
</body>
</html>