如何调用由同一构造函数创建的一组对象的所有方法

时间:2015-06-18 19:45:45

标签: javascript object methods

我正在尝试使用Java进入Java之后遇到问题。我有一个构造函数,它为每个对象提供this.move()方法,并将它们的名称添加到数组中。我想调用this.move()中的每个方法,这些方法由数组中的对象保存,但我无法想出办法。我的代码如下。

  var arrballs = [];
  var x;
  var y;
  var radius;
  var speed = 1;

  var startup = function startup() {
    var canvas1 = document.getElementById("canvas1");
    var context = canvas1.getContext("2d");
    context.fillStyle = "rgb(0, 0, 0)";
    context.fillRect(0, 0, 500, 500);
    var ball_1 = new ball(5, 0, 100, 100, 2);
  }

  var ball = function(radius, heading, xposition, yposition, speed) { //constructor for balls
    this.radius = radius;
    this.heading = heading; //in standard polar
    this.xposition = xposition;
    this.yposition = yposition;
    this.move = function move() {
    this.xposition = Math.cos(this.heading)*speed + this.xposition  //converts the heading to a unit vector and multiplies it by the scaler speed value
    this.yposition = Math.sin(this.heading)*speed + this.yposition
    }
    arrballs[arrballs.length] = "ball_" + arrballs.length + 1;
    }

    function drawScreen() {
        var canvas1 = document.getElementById("canvas1");
        var context = canvas1.getContext("2d");
        context.clearRect(0,0,500,500);
        for (i=0; i<arrballs.length; i++) {
            arrballs[i].move();
            context.beginPath();
            context.fillStyle = "red";
            context.arc(arrballs[i].xposition, arrballs[i].yposition, radius, 0, 2*Math.PI, false);
            context.fill();
            context.closePath();
        }
    }

为间距道歉,它被copypaste怪物吃掉了。

提前感谢您的帮助。

0 个答案:

没有答案