Eigendrea
Eigendrea

Reputation: 330

Invoke "superclass" constructor in JavaScript

I just got into JavaScript and I'm kind of puzzled by its object-oriented behavior. I was just trying to create a class Point2D with x,y members and extend it with a Point3D class with x,y,z members. The behavior I'm trying to achieve is something like, let's say it in 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; }
}

I read a lot of stuff but I don't seem to really find what I'm looking for. Here's what I've come up to so far:

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);

Which is obviously wrong.

Now, I know I should do something like Point3D.prototype = new A(x, y) but I don't want to create a prototype with fixed x,y coordinates and variable z. It must be very simple, but I'm just not getting it, I can't seem to call the superclass constructor or to make it behave properly.

Upvotes: 10

Views: 7932

Answers (1)

founddrama
founddrama

Reputation: 2411

JavaScript's prototypal inheritance provides a couple of different flexible ways to perform the kind of polymorphic constructors you're looking for. In your particular example, you want something like this:

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

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

Fussing with explicitly setting the constructor on the prototype is not strictly necessary here. (It is really only necessary when you are creating the prototype "all at once" -- e.g., with an object.)

For a detailed discussion of object-oriented JavaScript, I'd recommend Nicholas Zakas' Principles of Object-Oriented Programming in JavaScript (ebook) or the discussion of prototypes and inheritance in his other book, Professional JavaScript for Web Developers.

Upvotes: 17

Related Questions