Skip to content

Instantly share code, notes, and snippets.

@morganwilde
Created January 5, 2016 18:55
Show Gist options
  • Save morganwilde/7a58fcc7360f49d06e85 to your computer and use it in GitHub Desktop.
Save morganwilde/7a58fcc7360f49d06e85 to your computer and use it in GitHub Desktop.
ECMA 6 - Classes
"use strict";
class Point
{
constructor (coordinates) {
if (!(coordinates instanceof Array)) {
throw 'Error: Point constructor requires an array of coordinates.';
}
this._coordinates = coordinates;
}
// Getters
get coordinates () {
return this._coordinates;
}
get description () {
var description = '(';
let separator = ', ';
for (let coordinate of this.coordinates) {
description += coordinate + separator;
}
if (description.length > 1) {
description = description.substring(
0,
description.length - separator.length
);
}
return description + ')';
}
// Setters
set coordinates (coordinates) {
if (!(coordinates instanceof Array)) {
throw 'Error: Point coordinates must be an array.';
}
this._coordinates = coordinates;
}
countCoordinates () {
return this._coordinates.length;
}
}
class Point2D extends Point
{
constructor (x, y) {
super([x, y]);
}
// Getters
get x () {
return this._coordinates[0];
}
get y () {
return this._coordinates[1];
}
// Setters
set x (x) {
this._coordinates[0] = x;
}
set y (y) {
this._coordinates[1] = x;
}
}
var point = new Point2D(4, 6);
console.log(point); // Point {_coordinates: Array[2]}
console.log(point.countCoordinates()); // 2
console.log(point.constructor.name); // Point2D
console.log(point.description); // (4, 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment