个人平时常用的两种js类写法

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
   < html >
   < head >
     < meta  http-equiv ="content-type"  content ="text/html;charset=utf-8" />
     < script  type ="text/javascript" >
    
//  第一种
     var  Test1  =   function (){
        
var  name  =   "" ;
        
this .setName  =   function (username){
            name 
=  username;
        }
        
this .getName  =   function (){
            
return  name;
        }
        
this .sayHello  =   function (){
            
return   " Hello  "   +   this .getName();
        }
        
return   this ;
    }();
    Test1.setName(
" penngo " );
    console.log(
" Test1====== "   +  Test1.getName());
    console.log(
" Test1====== "   +  Test1.sayHello());

    
//  第二种
     var  Test2  =   function (){
        
var  name  =   "" ;
        
return  {
            setName:
function (username){
                name 
=  username;
            },
            getName:
function (){
                
return  name;
            },
            sayHello:
function (){
                
return   " Hello  "   +   this .getName();
            }
        };
    }();
    Test2.setName(
" penngo " );
    console.log(
" Test2====== "   +  Test2.getName());
        console.log(
" Test2====== "   +  Test2.sayHello());
    
</ script >
   </ head >
   < body >
   </ body >
   </ html >

你可能感兴趣的:(个人平时常用的两种js类写法)