2012-12-29 34 views
1
<script>  
    var Kevin = function(){ 
     this.name = 'kevin' 
    }   
    Kevin.prototype.getKevin = function(){   
     alert(this.name);   
    }    
    Kevin.prototype.getKevin(); 

    function John(){ 
    this.name = 'john' 
    }  
    John.getStaticJohn = function(){ 
    alert(this.name);  
    } 

    John.prototype.getJohn(); 
    John.getStaticJohn(); 

</script> 
  1. 的方法,這是爲什麼我在這兩種情況下使用原型調用 方法時得到undefined
  2. 當我嘗試在John類中調用靜態方法時,它會完美地打印 輸出。
+0

'Object.prototype'只允許您從外部擴展對象。調用它仍然依賴於首先定義的所述對象的實例。 –

回答

2

你得到undefined因爲原型沒有「name」屬性。還要注意,你對「getStaticJohn()」的調用實際上並沒有「完美地工作」 - 它用大寫字母「J」提醒「John」,因爲它正在訪問函數對象「John」的「name」屬性。

當您通過表格something.functionName的表達式調用方法時,函數內部的值this將始終爲值something。因此,當你調用

John.prototype.getJohn(); 

this的「getJohn()」函數中的值將是John.prototype,而不是由「約翰()」構造建造的任何實例。

如果添加此:

John.prototype.name = "John's prototype"; 

那麼你到John.prototype.getJohn()呼叫將提示比undefined以外的東西。

+0

你能帶我到原型的一篇不錯的文章,我可以完全理解這個概念。 – Kevin

4

如果你想叫從構造方法,你需要創建一個匿名實例:

(new Kevin).getKevin(); // or new Kevin().getKevin()