简体   繁体   中英

How to instantiate a class(ClassA) inside another class(ClassB) and use the ClassA object as a property in ClassB in JavaScript?

Consider the following code:

function Coord(x, y) {
    this.x = x;
    this.y = y;
}

function Ellipse() {
    this.Text = Text;
    this.Cx = Cx;
    this.Cy = Cy;
    this.Rx = Rx;
    this.Ry = Ry;
}

Now in the function Ellipse instead of using Cx , Cy etc. I want to instantiate the function Coord for each pair to achieve something as follows:

function Coord(x, y) {
    this.x = x;
    this.y = y;
}

function Ellipse() {
    this.Text = Text;
    Coord C = new C(); // where C has its own properties x and y
    Coord R = new R(); // where R has its own properties x and y
}

Try this:

function Coord(x, y) {
    this.x = x;
    this.y = y;
}

function Ellipse(text, cx, cy, rx, ry) {
    this.text = text;
    var c = new Coord(cx, cy);
    var r = new Coord(rx, ry);
}

I don't know how you thought of Coord C = new C() but it's absolutely wrong. JavaScript variables have no types.

Also from where are you getting Text , Cx , Cy , etc? Shouldn't they be passed as arguments to the constructor?

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