简体   繁体   English

如何在另一个类(ClassB)中实例化一个类(ClassA),并将ClassA对象用作JavaScript中ClassB的属性?

[英]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: 现在在函数Ellipse而不是使用CxCy等。我想为每对实例化函数Coord来实现以下目的:

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. 我不知道您如何看待Coord C = new C()但这是绝对错误的。 JavaScript variables have no types. JavaScript变量没有类型。

Also from where are you getting Text , Cx , Cy , etc? 另外,您从哪里获得TextCxCy等? Shouldn't they be passed as arguments to the constructor? 它们不应该作为参数传递给构造函数吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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