ruk·si

JS
Inheritance

Updated at 2013-04-28 09:21

In JavaScript, inheritance per se is not pre-defined but you can program it in a inherit way if you want.

/**
 * Point Superclass
 */
var Point = function(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.translate = function(x, y) {
  this.x += x;
  this.y += y;
}

/**
 * Point Usage
 */
var point = new Point(17, 42);
point.translate(5, 6);
console.assert(
  typeof point === 'object',
  'Type of the instance is still an object.'
);
console.assert(
  point instanceof Point,
  'The point is instance of Point.'
);
console.assert(
  point.constructor === Point,
  'The point object was created by the Point function a.k.a. constructor.'
);
/**
 * Point 3D Subclass
 */
var Point3d = function(x, y, z) {
  Point.call(this, x, y);
  this.z = z;
}
Point3d.prototype = new Point();
Point3d.prototype.translate = function(x, y, z) {
  Point.prototype.translate.call(this, x, y);
  this.z += z;
}

/**
 * Point 3D Usage
 */
var point3d = new Point3d(19, 20, 21);
point3d.translate(4, 5, 6);
console.assert(
  typeof point3d === 'object',
  'Type of the instance is still an object.'
);
console.assert(
  point3d instanceof Point,
  'The point3d is instance of Point.'
);
console.assert(
  point3d instanceof Point3d,
  'The point3d is instance of Point3d.'
);
console.log(point3d);
// => Object { x=23, y=25, z=27}