2011-11-04 51 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(); 
     }}