2011-11-04 50 views
1

這裏是類的一部分:公共陣列是不是JS類accessable

function Table(seats){ 
    //editables 
     var leaveTable_position=new Array('380','0','102','20'); 

    //runtime 
     Table.id=0; 
     Table.max_buy=0; 
     Table.min_buy=0; 
     Table.player_timeout=0; 

    //on creation 
     Table.seat=new Array(); 
     if (seats<5){seats=5;} 
     if (seats>5){seats=9;} 
     for (var i=1 ; i<=seats ; i++){ 
      Table.seat[i]=new Seat(i); 
      Table.seat[i].create(); 
     }} 

看到Table.seat公衆陣列? 假設我有3個席位(table.seat [0]; table.seat [2];)...

以下代碼給我'座位是未定義'!

table=new Table(); 
table.seat[2].getUser(); 

有什麼想法爲什麼?在js oop中不是很好!

+3

你可能想要閱讀這個關於javascript的OOP編程的MSDN教程:https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript。特別是,該javascript是基於Prototype的編程,其中「是一種面向對象的編程風格,其中不存在類,行爲重用(在基於類的語言中稱爲繼承)是通過裝飾現有對象的過程來完成的作爲原型「 – scrappedcola

回答

3

請勿使用Table使用this

例如:

//runtime 
    this.id=0; 
    this.max_buy=0; 
    this.min_buy=0; 
    this.player_timeout=0; 

見琴:http://jsfiddle.net/maniator/a7H57/3/

+0

哦,那很容易!謝謝 –

+0

@RonanDejhero您的歡迎!在我的回答中看到小提琴^ _ ^ – Neal

4

你必須使用this,而不是表。當使用Table時,您正在修改Table函數的屬性。

如果您使用this,則在Table「類」的當前實例上定義屬性。如果您仍想以Table爲前綴,則在您的函數中聲明var Table = this。這個副作用是你不能直接從函數內部調用Table()

function Table(seats){ 
     var Table = this; 
    //editables 
     var leaveTable_position=new Array('380','0','102','20'); 

    //runtime 
     Table.id=0; 
     Table.max_buy=0; 
     Table.min_buy=0; 
     Table.player_timeout=0; 

    //on creation 
     Table.seat=new Array(); 
     if (seats<5){seats=5;} 
     if (seats>5){seats=9;} 
     for (var i=1 ; i<=seats ; i++){ 
      Table.seat[i]=new Seat(i); 
      Table.seat[i].create(); 
     }}