服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

javascript中最流行的2种定义类的方式

其它方式:工厂方式,构造函数方式,原型方式都各有各的大缺陷,这里就不一一介绍了,想了解的可以去看一下这本著作的第3章节。

1. 混合构造函数/原型方式 

  1. function  car(scolor, idoors, impg) {
  2.    this .color  =  scolor;
  3.    this .doors  =  idoors;
  4.    this .mpg  =  impg;
  5.    this .drivers  =   new  array(“mike”, “sue”);
  6. }
  7. car.prototype.showcolor  =   function  () {
  8.   alert( this .color);
  9. };
  10. var  ocar1  =   new  car(“red”,  4 ,  23 );
  11. var  ocar2  =   new  car(“blue”,  3 ,  25 );
  12. ocar1.drivers.push(“matt”);
  13. alert(ocar1.drivers);  // outputs “mike,sue,matt” 
  14. alert(ocar2.drivers);  // outputs “mike,sue”
 

优点:具有其它方式的优点而没有其它方式的缺点
不足:封装性欠缺

2 . 动态原型方式 
  1.   function  car(scolor, idoors, impg)   {
  2.    this .color  =  scolor;
  3.    this .doors  =  idoors;
  4.    this .mpg  =  impg;
  5.    this .drivers  =   new  array(“mike”, “sue”);
  6.    if  ( typeof  car._initialized  ==  “undefined”)   {
  7.     car.prototype.showcolor  =   function  ()   {
  8.       alert( this .color);
  9.     } ;
  10.     car._initialized  =   true ;
  11.   } 


优点:封装性比上一个方式更好
不足:就是看上去奇怪一点,呵呵 

总之,以上2种方式是目前最广泛使用的,尽量使用它们避免不必要的问题。