JS中的phototype是JS中比較難理解的一個部分javascript
本文基於下面幾個知識點:java
1 原型法設計模式設計模式
在.Net中可使用clone()來實現原型法函數
原型法的主要思想是,如今有1個類A,我想要建立一個類B,這個類是以A爲原型的,而且能進行擴展。咱們稱B的原型爲A。測試
2 javascript的方法能夠分爲三類:this
a 類方法spa
b 對象方法prototype
c 原型方法設計
例子:code
function People(name) { this.name=name; //對象方法 this.Introduce=function(){ alert("My name is "+this.name); } } //類方法 People.Run=function(){ alert("I can run"); } //原型方法 People.prototype.IntroduceChinese=function(){ alert("個人名字是"+this.name); } //測試 var p1=new People("Windking"); p1.Introduce(); People.Run(); p1.IntroduceChinese();
3 obj1.func.call(obj)方法
意思是將obj當作obj1,調用func方法
好了,下面一個一個問題解決:
prototype是什麼含義?
javascript中的每一個對象都有prototype屬性,Javascript中對象的prototype屬性的解釋是:返回對象類型原型的引用。
A.prototype = new B();
理解prototype不該把它和繼承混淆。A的prototype爲B的一個實例,能夠理解A將B中的方法和屬性所有克隆了一遍。A能使用B的方 法和屬性。這裏強調的是克隆而不是繼承。能夠出現這種狀況:A的prototype是B的實例,同時B的prototype也是A的實例。
先看一個實驗的例子:
function baseClass() { this.showMsg = function() { alert("baseClass::showMsg"); } } function extendClass() { } extendClass.prototype = new baseClass(); var instance = new extendClass(); instance.showMsg(); // 顯示baseClass::showMsg
咱們首先定義了baseClass類,而後咱們要定義extentClass,可是咱們打算以baseClass的一個實例爲原型,來克隆的extendClass也同時包含showMsg這個對象方法。
extendClass.prototype = new baseClass()就能夠閱讀爲:extendClass是以baseClass的一個實例爲原型克隆建立的。
那麼就會有一個問題,若是extendClass中自己包含有一個與baseClass的方法同名的方法會怎麼樣?
下面是擴展實驗2:
function baseClass() { this.showMsg = function() { alert("baseClass::showMsg"); } } function extendClass() { this.showMsg =function () { alert("extendClass::showMsg"); } } extendClass.prototype = new baseClass(); var instance = new extendClass(); instance.showMsg();//顯示extendClass::showMsg
實驗證實:函數運行時會先去本體的函數中去找,若是找到則運行,找不到則去prototype中尋找函數。或者能夠理解爲prototype不會克隆同名函數。
那麼又會有一個新的問題:
若是我想使用extendClass的一個實例instance調用baseClass的對象方法showMsg怎麼辦?
答案是可使用call:
extendClass.prototype = new baseClass(); var instance = new extendClass(); var baseinstance = new baseClass(); baseinstance.showMsg.call(instance);//顯示baseClass::showMsg
這裏的baseinstance.showMsg.call(instance);閱讀爲「將instance當作baseinstance來調用,調用它的對象方法showMsg」
好了,這裏可能有人會問,爲何不用baseClass.showMsg.call(instance);
這就是對象方法和類方法的區別,咱們想調用的是baseClass的對象方法
最後,下面這個代碼若是理解清晰,那麼這篇文章說的就已經理解了:
<script type="text/javascript"> function baseClass() { this.showMsg = function() { alert("baseClass::showMsg"); } this.baseShowMsg = function() { alert("baseClass::baseShowMsg"); } } baseClass.showMsg = function() { alert("baseClass::showMsg static"); } function extendClass() { this.showMsg =function () { alert("extendClass::showMsg"); } } extendClass.showMsg = function() { alert("extendClass::showMsg static") } extendClass.prototype = new baseClass(); var instance = new extendClass(); instance.showMsg(); //顯示extendClass::showMsg instance.baseShowMsg(); //顯示baseClass::baseShowMsg instance.showMsg(); //顯示extendClass::showMsg baseClass.showMsg.call(instance);//顯示baseClass::showMsg static var baseinstance = new baseClass(); baseinstance.showMsg.call(instance);//顯示baseClass::showMsg </script>