javascript - 在 js 类中无法访问公共(public)数组

标签 javascript oop

这是类(class)的一部分:

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 公共(public)数组了吗? 假设我有 3 个座位 (table.seat[0]; table.seat[2];) ...

下面的代码给我“座位未定义”!!!

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

有什么想法吗?在 js oop 方面不是很好!

最佳答案

您必须使用 this 而不是 Table。使用 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();
        }}

关于javascript - 在 js 类中无法访问公共(public)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8013134/

相关文章:

c# - OOP设计: how to model a company which can be a debtor, 债权人、领导还是只是一种关系?

C++抽象类继承虚函数

c++ - 锁定取消引用的互斥量是不好的行为吗?

javascript - 如何编写一个数组过滤器,返回另一个数组中的所有数组项

javascript - 正则表达式获取字符之间的所有字符

javascript - select2 不加载 ajax 数据 : TypeError: c. ajax 不是函数

javascript - 将多个预编译模板与 Handlebars .js(多个 HTTP 请求)一起使用?

javascript - 检查 YouTube 播放器是否使用 HTML5/Flash

java - 子类java中具有相同名称的属性

java - 从具体类派生的抽象类