简体   繁体   中英

How to call a method from an object in an object in javascript?

I am new to oop javascript and I was wondering if someone could help me how to correctly call a method from an object in an object. Making the circlegarden seems to work and I can even call a circle from that garden. But whenever I want to call x, it stops working...

Here is the code:

var cg = new circlegarden(4);
var testx = cg.getCircle(0).getx();

function circle(x, y, vx, vy, dv, color) {
    this.x=x;
    this.y=y;
    this.vx=vx;
    this.vy=vy;
    this.dv=dv;
    this.color=color;
    this.vertices = [0.0, 0.0, 0.0];
    for(var i = 0; i <= 40; i++) {
        this.vertices.push(Math.cos((2 * Math.PI)/40)); 
        this.vertices.push(Math.sin((2 * Math.PI)/40)); 
        this.vertices.push(0); 
    }
    this.getx = function() {
        return this.x;
    }
    //other methods...
}

function circlegarden(n) {
    this.n=n;
    this.circles=new Array();
    for(var i = 0; i < this.n; i++) {
        this.circles.push(2*Math.cos((2 * Math.PI)/this.n), 2*Math.sin((2 * Math.PI)/this.n), 2*(Math.random()-.5), 2*(Math.random()-.5), 0.02, i);
    }
    this.wall=[[-2.9, -2.5, 2.9, -2.5], [-2.9, 2.5, 2.9, 2.5], [-2.9, -2.5, -2.9, 3], [2.9, -2.5, 2.9, 2.5]];

    this.getCircle = function(i) {
        return this.circles[i];
    }
    //other methods...
}

You didn't create circles in that for-loop. You should use new circle(2*Math.cos((2 * Math.PI)/this.n), 2*Math.sin((2 * Math.PI)/this.n), 2*(Math.random()-.5), 2*(Math.random()-.5), 0.02, i) to create that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM