时间:2021-07-01 10:21:17 帮助过:4人阅读
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>
源代码打包下载