|
.定義namespace
Namesapce.js
復制代碼 代碼如下:
Namespace = new Object();
Namespace.register = function(fullname){
try
{
var nsArray = fullname.split(".");
var strNS = "";
var strEval = "";
for(var i=0;i<nsArray.length;i++){
if(strNS.length >0)
strNS += ".";
strNS += nsArray[i];
strEval += " if(typeof("+ strNS +") =='undefined') " + strNS + " = new Object(); ";
}
if(strEval != "") eval(strEval);
}catch(e){alert(e.message);}
}
.Employee.js
Employee.js
復制代碼 代碼如下:
//注冊命名空間
Namespace.register("MyCompany");
//1.類:雇員
MyCompany.Employee = function(empName){
this.Name = empName;
this.Salary = 1000;
this.Position = "cleaner";
}
MyCompany.Employee.prototype.ShowName = function(){
return "I'm "+this.Name+",my salary is $" + this.Salary;
}
MyCompany.Employee.prototype.Work = function(){
return "I'm a "+ this.Position +",I'm cleaning all day!"
}
//2.類:程序員
MyCompany.Developer = function(empName){
//繼承父類屬性
MyCompany.Employee.call(this,empName);
//覆蓋父類屬性
this.Position = "developer";
//擴展屬性
this.Technology = "C#";
}
//繼承父類原型方法
MyCompany.Developer.prototype = new MyCompany.Employee();
//覆蓋父類方法
MyCompany.Developer.prototype.Work = function(){
return "I'm a "+ this.Position +",i'm good at "+ this.Technology +",i'm coding all day!"
}
測試代碼
復制代碼 代碼如下:
<html>
<title>Javascript 面向對象的實現 namespace,class,繼承,重載</title>
<head>
<script language="Javascript" src="namespace.js" type="text/Javascript"></script>
<script language="Javascript" src="employee.js" type="text/Javascript"></script>
<script language="Javascript" type="text/Javascript">
function showEmployee(){
var emp = new MyCompany.Employee("xiaoming");
showInfo(emp);
}
function showDeveloper(){
var emp = new MyCompany.Developer("Gates");
showInfo(emp);
}
function showInfo(emp){
alert(emp.ShowName());
alert(emp.Work());
}
</script>
</head>
<body>
<input type="button" value="show employee info" onclick="showEmployee();"/><br/><br/>
<input type="button" value="show developer info" onclick="showDeveloper();"/>
</body>
</html>
源代碼打包下載
JavaScript技術:javascript 面向對象,實現namespace,class,繼承,重載,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。