Heptic
Heptic

Reputation: 3106

Very simple Javascript inheritance

I need a super-readable version of this super simple inheritance in JavaScript. This is some auto-generated code, where I can't afford to be using external functions or libraries.

What I really want is, assuming Point3d "inherits" from Point, I want something like this:

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

function Point3d(x,y,z) {
  Point(x, y);
  this.z = z;
}

Except it doesn't actually work:

var pt = new Point3d(230,30,11);
// but x and y are in global scope, they should be in pt.x and pt.y :(

One possible option, would in the code generation duplicate all the members -- but since Javascript is prototype based, I would imagine this is easy to do properly (if I actually knew Javascript)

Thanks

Upvotes: 1

Views: 218

Answers (2)

evil otto
evil otto

Reputation: 10582

You need to create an object to begin with.

function Point(x,y) {
  return { x: x, y: y }
}

function Point3d(x,y,z) {
  var self=new Point(x, y);
  self.z=z;
  return self;
}
var pt = new Point3d(230,30,11);

Upvotes: 1

user1106925
user1106925

Reputation:

Apply the Point constructor to the Point3d object using .call().

function Point3d(x,y,z) {
  Point.call(this, x, y);
  this.z = z;
}

http://jsfiddle.net/MSfu5/

The .call method sets the value of this in the function you're calling.

Here we're setting it to the new Point 3d object being constructed.


If there's anything on the Point prototype that Point3d should inherit, you can make the Point3d.prototype object an empty instance of Point.

Upvotes: 8

Related Questions