Home  >  Article  >  Web Front-end  >  javascript object-oriented, implement namespace, class, inheritance, overloading_js object-oriented

javascript object-oriented, implement namespace, class, inheritance, overloading_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:43:021103browse

Since most of the client-side work such as JavaScript and CSS in the group was handled by another colleague, and that colleague was too busy to refactor, the boss only made suggestions and did not immediately implement the refactoring. But I also fixed some small bugs in the client a few days ago. The code is indeed a bit confusing. I don’t know where I am, and I don’t dare to touch the code easily, so I tinkered with it myself. I once loved and hated it. Using javascript, write a simple js to implement namespace, inheritance, overloading and other object-oriented features. Welcome to contribute
. Define namespace
Namesapce.js

Copy code The code is as follows:

Namespace = new Object();
Namespace.register = function(fullname){
try
{
var nsArray = fullname.split(".");
var strNS = "";
var strEval = "";
for(var i=0;iif(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 The code is 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 is $" 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){
// Inherit parent class properties
MyCompany.Employee.call(this,empName);
//Override parent class properties
this.Position = "developer";
//Extend properties
this. Technology = "C#";
}
//Inherit the parent class prototype method
MyCompany.Developer.prototype = new MyCompany.Employee();
//Override the 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 The code is as follows:

javascript object-oriented implementation namespace, class, inheritance, overloading