javascript prototype分析

對(duì)于Javascript的初學(xué)者來(lái)說(shuō),Prototype是個(gè)蠻高深的話(huà)題,其實(shí)并不盡然。

  我說(shuō)不盡然,意思是說(shuō)理解Prototype的一般用法很簡(jiǎn)單。但是真正能做到融會(huì)貫通理解Prototype確實(shí)是件很難的事情。

  今天我就從Prototype的基本開(kāi)始講。上文中我講了原型模式。其實(shí)在Javascript中原型也是這個(gè)意思。 Javascript中對(duì)象的原型屬性的解釋是:返回對(duì)象類(lèi)型原型的引用。這是一個(gè)暈人的解釋。其實(shí)就是指定了一個(gè)需要復(fù)制的對(duì)象。

  文字再多也不如代碼,上代碼,說(shuō)最簡(jiǎn)單的,任何類(lèi)都繼承自O(shè)bject類(lèi):

function A()
{

//todo something

}
A.prototype=new Object();

  其實(shí)這樣就相當(dāng)于Object對(duì)象是A的一個(gè)原型,這樣就相當(dāng)于了把Object對(duì)象的屬性和方法復(fù)制到了A上,和原型模式的精髓一樣吧!

  好,大概了解了prototype的基本用法,我們來(lái)看看原型究竟有什么用處。

  最簡(jiǎn)單的用法,動(dòng)態(tài)擴(kuò)展類(lèi)的方法和屬性。

de>function People()
{
   this.Jump=function(){
                                alert("I can jump");
                                           }
}

  現(xiàn)在要擴(kuò)充方法:

People.prototype.Run=function(){
                                    alert("I can run,too");
                                                    }

  好,測(cè)試下:

var p=new People();
p.Jump();
p.Run();

cript玩轉(zhuǎn)Prototype - Gabriel - Software Engineer" height=153 alt="Javascript玩轉(zhuǎn)Prototype(二)" src="http://hiphotos.baidu.com/yafengyouxia/pic/item/9f99f91faaa8f027f724e4a1.jpg" width=231>

cript玩轉(zhuǎn)Prototype - Gabriel - Software Engineer" height=138 alt="Javascript玩轉(zhuǎn)Prototype(二)" src="http://hiphotos.baidu.com/yafengyouxia/pic/item/2bd66063e085f0240d33faa1.jpg" width=217>

  接下來(lái),順帶講一下Javascript的方法種類(lèi)。我個(gè)人將Javascript的方法分為三種:

  <1>類(lèi)方法

  <2>對(duì)象方法

  <3>原型方法

  先看代碼,后講區(qū)別:

function People(name)
{
this.name=name;
//對(duì)象方法
this.Introduce=function(){
alert("My name is "+this.name);
}
}
//類(lèi)方法
People.Run=function(){
alert("I can run");
}
//原型方法
People.prototype.IntroduceChinese=function(){
alert(" 我的名字是"+this.name);
}

  測(cè)試下:

var p1=new People("Windking");
p1.Introduce();
People.Run();
p1.IntroduceChinese();

cript玩轉(zhuǎn)Prototype - Gabriel - Software Engineer" height=124 alt="Javascript玩轉(zhuǎn)Prototype(二)" src="http://hiphotos.baidu.com/yafengyouxia/pic/item/63fb606014921c00eaf8f8a1.jpg" width=203>

cript玩轉(zhuǎn)Prototype - Gabriel - Software Engineer" height=140 alt="Javascript玩轉(zhuǎn)Prototype(二)" src="http://hiphotos.baidu.com/yafengyouxia/pic/item/99ec8c44f1598108500ffea1.jpg" width=209>

cript玩轉(zhuǎn)Prototype - Gabriel - Software Engineer" height=136 alt="Javascript玩轉(zhuǎn)Prototype(二)" src="http://hiphotos.baidu.com/yafengyouxia/pic/item/7e27114c4dae42bdd62afca1.jpg" width=216>

  總結(jié)下: