1024programmer Java javascript object-oriented, implement namespace, class, inheritance, overloading_js object-oriented

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

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. Javascript, write a simple js to implement namespace, inheritance, overloading and other object-oriented features. Welcome to contribute
. Define namespace
Namesapce.js

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;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

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 attributes
MyCompany.Employee.call(this,empName);
//Override parent class attributes
this.Position = “developer”;
//Extend attributes
this.Technology = “C#”;
}
//Inherit parent class prototype Method
MyCompany.Developer.prototype = new MyCompany.Employee();
//Override 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

The code is as follows:





Source code package download

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/javascript-object-oriented-implement-namespace-class-inheritance-overloading_js-object-oriented/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索