Loading

Javascript之面向对象

       Javascript作为弱类型语言,拥有极强的灵活性。在面对小型web需求是,编写javascript,可以选择面向过程的方式编程;但是遇到项目需求和框架较大的情况下,选择面向对象的方式编程,显得高效。但是同时使得代码结构变得复杂,而且会带来一些额外的内存开销,这些仍需注意。

1、命名空间。

/**
 * @author KKThink
 */
//命名空间定义
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);
        }
  
}
//命名空间定义
Namespace.register("MyCompany");

MyCompany.Employee=function(employeename){
    this.Name=employeename;
    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"+this.Position+",I'm cleaning all day!";
}


MyCompany.Developer=function(employeename){
    MyCompany.Employee.call(this,employeename);//继承父类属性
    this.Name="developer";
    this.Sarary=9999;
    this.Technology="C Sharp!";
}
MyCompany.Developer.prototype.Work=function(){
    return "I'm a"+this.Name+",I'm good at"+this.Technology+",I'm coding all day!"
}

2、类

我们如何在javascript中定义类?利用function关键字,来定义类,类名首字母一般采用大写。

MyCompany.Employee=function(employeename){
    this.Name=employeename;//定义类属性
    this.Salary=1000;
    this.Position="cleaner";
}

定义public方法:

MyCompany.Employee.prototype.ShowName=function(){
    return "I'm"+this.Name+",my salary is $"+this.Salary;
}//定义方法
MyCompany.Employee.prototype.Work=function(){
    return "I'm"+this.Position+",I'm cleaning all day!";
}

3、实现继承

MyCompany.Developer=function(employeename){
    MyCompany.Employee.call(this,employeename);//继承父类employee属性
    this.Name="developer";//覆盖父类属性
    this.Sarary=9999;
    this.Technology="C Sharp!";//扩展父类属性
}
MyCompany.Developer.prototype.Work=function(){//覆盖父类方法
    return "I'm a"+this.Name+",I'm good at"+this.Technology+",I'm coding all day!"
}
posted @ 2012-06-27 23:07  Cooper_Liu  阅读(309)  评论(0编辑  收藏  举报