代码之家  ›  专栏  ›  技术社区  ›  fighg

使用对象数组访问类函数

  •  1
  • fighg  · 技术社区  · 7 年前

    我在p5中编写代码。js,我注意到一个我无法通过的问题。

    我有一个名为“盒子”的类。我已经在使用“盒子”的功能了。但是,虽然我尝试将函数应用于对象数组,但它不起作用。如何解决此问题?

    class Boxes
    {
        constructor()
        {
            this.x;
            this.y;
            this.r=222;
            this.g=55;
            this.b=111;
        }
    
        show()
        {
            fill(this.r,this.g,this.b);
            rect(this.x,this.y,50,50);
        }
    }
    

    对于标准变量,它的工作原理与此完全相同。

    var box1 = new Boxes();
    box1.show(); // It works.
    

    当我尝试不同的东西时,它不起作用。下面的示例。

    var myboxes = [{'x':this.x, 'y':this.y}]; // That's OK :)
    
    myboxes.push({x:100, y:100}); // That's OK too :)
    
    myboxes[1].show(); // But. It gives an error :/
    

    上面写着:“MyBox[1]。show不是一个函数”

    虽然我编写了show()函数,但使用括号。上面写着 “MyBox[1]。show不是一个函数”当我使用 方框1。显示()。如何使用对象数组访问函数? 我要不要试试别的?你有什么建议?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Eddie    7 年前

    如果您想拥有 盒子 ,你可以。 push() 新对象包括:

    class Boxes {
      constructor(param) {
        this.x = param.x;                     //Assign the x   
        this.y = param.y;                     //Assign the y
        this.r = 222;
        this.g = 55;
        this.b = 111;
      }
    
      show() {
        console.log(this.x, this.y);          //Test code,
    
        //fill(this.r,this.g,this.b);
        //rect(this.x,this.y,50,50);
      }
    }
    
    var myboxes = [];
    myboxes.push(new Boxes({x: 3,y: 20}));     //Create a new box and push to the array
    myboxes.push(new Boxes({x: 30,y: 200}));   //Create anothe one and push to the array
    
    myboxes[1].show();                         //<-- You can show the x and y of element 1
        2
  •  0
  •   CertainPerformance    7 年前

    如果创建非长方体对象,它没有 show 原型链中的任何位置。但这没关系,如果您有权访问该类,则可以使用non-box对象作为 this :

    class Boxes {
      show() {
        console.log(this.x);
      }
    }
    
    var myboxes = [{'x':this.x, 'y':this.y}];
    myboxes.push({x:100, y:100});
    Boxes.prototype.show.call(myboxes[1]);

    但请注意,您还需要 r ,则, g b 非长方体对象上的属性,以便 显示 工作。