【问题标题】:Invoke "superclass" constructor in JavaScript在 JavaScript 中调用“超类”构造函数
【发布时间】:2013-01-15 19:05:30
【问题描述】:

我刚接触到 JavaScript,我对它的面向对象的行为有点困惑。 我只是想用x,y 成员创建一个Point2D 类,并用Point3D 类和x,y,z 成员扩展它。 我试图实现的行为类似于,让我们在 C# 中说:

class Point2D
{ 
   int x, y;
   public Point2D(int x, int y) { this.x = x; this.y = y; }
}
class Point3D : Point2D
{
    int z;
    public Point3D(int x, int y, int z) : base(x, y) { this.z = z; }
}

我阅读了很多东西,但似乎并没有真正找到我想要的东西。 到目前为止,这是我的想法:

function Point2D(x, y) { this.x = x; this.y = y; }
Point2D.prototype.constructor = Point2D;
function Point3D(x, y, z) { Point2D.prototype.constructor.call(this); this.z = z; }
Point3D.prototype = new A(); // see latter explanation
Point3D.prototype.constructor = B;
var p = new Point3D(10, 20, 30);

这显然是错误的。

现在,我知道我应该执行Point3D.prototype = new A(x, y) 之类的操作,但我不想创建具有固定 xy 坐标和变量z 的原型。 它一定很简单,但我就是不明白,我似乎无法调用超类构造函数或使其行为正常。

【问题讨论】:

    标签: javascript inheritance polymorphism


    【解决方案1】:

    JavaScript 的原型继承提供了几种不同的灵活方式来执行您正在寻找的多态构造函数。在您的特定示例中,您想要这样的东西:

    function Point2D(x, y) {
      this.x = x;
      this.y = y;
    }
    
    function Point3D(x, y, z) {
      Point2D.call(this, x, y);
      this.z = z;
    }
    

    prototype 上显式设置constructor 并不是绝对必要的。 (仅当您“一次性”创建原型时才需要这样做——例如,使用一个对象。)

    关于面向对象的 JavaScript 的详细讨论,我推荐 Nicholas Zakas 的 Principles of Object-Oriented Programming in JavaScript(电子书)或在他的另一本书中讨论原型和继承, 面向 Web 开发人员的专业 JavaScript

    【讨论】:

    • 非常感谢,我快疯了,就这么简单!我肯定会至少阅读其中一本书。
    猜你喜欢
    • 2013-07-19
    • 2015-12-18
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多