Because most of the project JAVASCRIPT,CSS client work is another colleague in charge, the colleague and special busy can not be reconstructed, the boss also just make suggestions did not immediately implement refactoring. But I've also changed a little bit of client bugs in the last few days, it is true that the code is a little foggy, I do not know which mountain, easy to move code, so I started to tinker with the love and hate of JavaScript, write a simple JS implementation namespace, inheritance, Object-oriented features such as overloading. Welcome to the Brick irrigation
. Define Namespace
Namesapce.js
Copy Code code as follows:
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
Copy Code code as follows:
//Register namespace
Namespace.register ("MyCompany");
//1. Class: Employee
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 are $" + this. Salary;
}
MyCompany.Employee.prototype.Work = function () {
return "I ' m a" + this. Position + ", I ' m cleaning all day!"
}
//2. Class: Programmer
Mycompany.developer = function (empname) {
//Inheriting parent class properties
MyCompany.Employee.call (this,emp Name);
//Overwrite parent class properties
this. Position = "Developer";
//Extended Properties
this. Technology = "C #";
}
//inherits the parent class prototype method
MyCompany.Developer.prototype = new Mycompany.employee ();
//Overwrite parent class method
MyCompany.Developer.prototype.Work = function () {
return "I ' m a" + this. Position + ", I ' m good at" + this. Technology + ", I ' m coding all day!"
}
Test code
Copy Code code as follows:
<title>javascript Object-oriented implementation Namespace,class, inheritance, overload </title>
<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>
<body>
<input type= "button" value= "Show employee Info" onclick= "Showemployee ();" /><br/><br/>
<input type= "button" value= "Show developer Info" onclick= "showdeveloper ();" />
</body>
Source code Package Download