提点:

1、JavaScript是HTML辅助作用的弱类型语言,它的对象可以是:声明的变量,函数,{}等等。

2、JavaScript也可以面向对象:因为js语言比较灵活,它提供的函数也可以作为一个对象,通过new 关键字来产生一个实例。

3、实现对属性和方法的封装,最终形成类;类是抽象的,对象是具体的;但是Javascript中可以混合使用,这正体现了Javascript作为编程语言与其他语言比较下的最大优势,以致这种灵活性的编程方式令其他语言望尘莫及。

示例:

 /**
  *声明一个类似于java的类并添加其属性
  */
 var User=function(){
   var name='jack';//默认值
   var gender='male';//默认值
   var age=20;//默认值
   this.setName=function(name){
        this.name=name;
  };
   this.getName=function(){
       return this.name;
  };
   this.setGender=function(gender){
       this.gender=gender;
  };
  this.getGender=function(){
    return this.gender;
  };
  this.setAge=function(age){
       this.age=age;
  };
  this.getAge=function(){
     return this.age;
  };
  this.introduceMyself=function(){
     alert('Hello!my name is '+this.getName()+",I'm "+this.getAge()+'years old!');
  };
}

/**

*其他几种简写方法及调用

*/

//内部类的方法和属性 
   var people=function(kind,color,life){
     this.kind=kind;
     this.life=life;
     this.color=color;
     this.infos=function(){
       alert('kind :'+kind+' color: '+color+' life :'+life);
     }
   } 
   function description(){
    //创建一个实例并调用其方法 
     new people('America','white',61).infos();
   }
  //设置一个实体类 
   function User(){
      this.name="Ben";
      this.age=21;
      this.email="yk_ben@123.com";
      this.work='student';
      this.sex='man';
   }
   //实例对象的创建和使用 
   var user=new User();
   //调用实例
   function sayHi(){
      alert('Hello everyone!I am '+user.name);
   }
   //为实体对象添加方法
   user.info=function(){
      var call=user.sex=='man'?'He':'She', alias=user.sex=='man'?'boy':'girl';
      alert('This is '+user.name+"'s information: "+call+' is a '+alias+' and '+
             call+' is '+user.age+' years old!');
   }
   function info(){
      user.info();
   }
   user.str=function(){alert(this.name+this.email+this.sex+this.age+this.work);}
   function str(){
      user.str();
   }
   //创建无类型类
   var teacher={name:'TomShen'};
   function seeName(){
     alert('Teacher name is '+teacher.name);
   }

 

 

相关文章:

  • 2021-08-18
  • 2021-10-21
  • 2021-08-25
  • 2021-09-14
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-27
  • 2021-12-11
  • 2021-10-17
  • 2021-09-25
  • 2021-09-24
相关资源
相似解决方案