JS 创建对象(常见几种)

来源:互联网 发布:淘宝定制类目有多少家 编辑:程序博客网 时间:2024/05/21 02:20

贴个代码先:

  1. function O(user,pwd){       //use constructor
  2.     this.user=user;
  3.     this.pwd=pwd;
  4.     this.get=get;
  5.     return this;
  6.  }
  7.   function O2(user,pwd){   //use factory  
  8.   var obj=new Object();
  9.     obj.user=user;
  10.     obj.pwd=pwd;
  11.     obj.get=get;
  12.     return obj;
  13.  }
  14.  function O3(){         //use   prototype
  15.  }
  16.  O3.prototype.user='abc';
  17.  O3.prototype.pwd='dis';
  18. // O3.propotype.get='get';
  19. //O3.prototype.get(){
  20.     //alert(this.pwd);
  21. //}
  22. function O4(user,pwd){
  23.     this.user=user;
  24.     this.pwd=pwd;
  25.     return this;
  26. }
  27.     O4.prototype.get=function(){alert('123');}
  28.  //function get(){
  29.     //alert("This User:"+this.user);
  30. // }
  31.  function test2(){
  32.     //var a=new O2('Us','Pw');  use factory & constructor
  33.     //var a=new O3();   //use prototype
  34.     //a.get();
  35.     var a=new O4('*U4','P4');      //混合
  36.     //a.user='Not ABC';   //set new property
  37.     //alert(a.user);
  38.     a.get();
  39.  }

常用的MS 就这几种,可能还有其它的.碰到再说吧....