2015-07-04 30 views
0

我想創建靜態變量和靜態函數。但是當我訪問它時,它給了我undefined爲什麼? 這裏是我的功能爲什麼靜態變量不顯示輸出?

function Shape(){ 
     this.namev="naven" 
     Shape.PIe="3.14"; 
     Shape.getName=function(){ 
      return "nveen test shhsd" 
     } 

    } 

    alert(Shape.PIe) 
    alert(Shape.getName()) 
+0

getName()是「靜態的」,因爲它肯定會返回與特定實例關聯的名稱屬性?我建議你找一個關於JavaScript的基於原型的繼承的教程,然後考慮是否直接向'Shape'添加屬性是最好的方法。 – nnnnnn

回答

3

Shape.getName()功能後才進行初始化後Shape()被稱爲第一次(初始化代碼是Shape()內),所以因此Shape.getName性不存在,直到Shape()被調用。

也許你想要的是這樣的:

// define constructor that should only be called with the new operator 
function Shape() { 
    this.namev="naven"; 
} 

// define static methods and properties 
// that can be used without an instance 
Shape.PIe="3.14"; 
Shape.getName=function(){ 
    return "nveen test shhsd" 
} 

// test static methods and properties 
alert(Shape.PIe) 
alert(Shape.getName()) 

請記住,在JavaScript中的函數是一個對象,可以有它自己的屬性,就像一個普通的對象。因此,在這種情況下,您只需使用Shape函數作爲可以將靜態屬性或方法放在其上的對象。但是,不要指望在靜態方法中使用this,因爲它們沒有連接到任何實例。它們是靜態的。


如果你想可以唯一訪問Shape對象實例的實例的屬性或方法,那麼你就需要創建的方法和屬性不同(例如以來方法或屬性不是靜態的)。

+0

解決方案是什麼? – user944513

+0

@ user944513 - 將代碼添加到答案中。 – jfriend00

1

要建立由所有實例共享一個靜態變量,你需要聲明它的函數聲明之外,像這樣:

function Shape() { 
    // ... 
} 

Shape.PIe = "3.14"; 

alert(Shape.PIe); 

看到這個職位的詳細信息,你如何能「翻譯」一些將熟悉的OOP訪問概念轉換爲Javascript:https://stackoverflow.com/a/1535687/1079597

相關問題