你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對象實例的實例的屬性或方法,那麼你就需要創建的方法和屬性不同(例如以來方法或屬性不是靜態的)。
getName()是「靜態的」,因爲它肯定會返回與特定實例關聯的名稱屬性?我建議你找一個關於JavaScript的基於原型的繼承的教程,然後考慮是否直接向'Shape'添加屬性是最好的方法。 – nnnnnn