小方的Java博客

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  27 随笔 :: 17 文章 :: 115 评论 :: 0 Trackbacks
选自《Professional Javascript For Web Developers》

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

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

function  Car(sColor, iDoors, iMpg) {
  
this .color  =  sColor;
  
this .doors  =  iDoors;
  
this .mpg  =  iMpg;
  
this .drivers  =   new  Array(“Mike”, “Sue”);
}

Car.prototype.showColor 
=   function  () {
  alert(
this .color);
};

var  oCar1  =   new  Car(“red”,  4 23 );
var  oCar2  =   new  Car(“blue”,  3 25 );

oCar1.drivers.push(“Matt”);

alert(oCar1.drivers); 
// outputs “Mike,Sue,Matt”
alert(oCar2.drivers);  // outputs “Mike,Sue”

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

2 . 动态原型方式

function  Car(sColor, iDoors, iMpg)  {
  
this .color  =  sColor;
  
this .doors  =  iDoors;
  
this .mpg  =  iMpg;
  
this .drivers  =   new  Array(“Mike”, “Sue”);

  
if  ( typeof  Car._initialized  ==  “undefined”)  {
    Car.prototype.showColor 
=   function  ()  {
      alert(
this .color);
    }
;

    Car._initialized 
=   true ;
  }

}


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


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

posted on 2007-02-11 17:34 方佳玮 阅读(6146) 评论(1)  编辑  收藏 所属分类: AJAX

评论

# re: [整理]JavaScript最流行的2种定义类的方式 2007-02-11 20:46 BeanSoft
// Method 1: flat array style quick object define
var myObject = {
username : "beansoft",
age : 24,
test : function() {alert(this.age);}
};

// Method 2: using Object
var myObject = new Object();
myObject.username = "beansoft";
myObject.age = 24;

// Method 3: using constructor

function MyObject(username, age) {
this.username = username;
this.age = age;
this.test = function() {alert(this.age);};
}

var myObject = new MyObject("beansoft", 24);

// Method 4,5 如楼上文章所言既是

// Using: myObject.username, myObject["username"], myObject[0]
myObject.test();// Will display alert window, value is age
myObject.username = "Hello";// Will asign the username property to "Hello"  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: