Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active December 6, 2016 07:00
Show Gist options
  • Save magnetikonline/a00d4b81745ba81363b5d4c8d010ce93 to your computer and use it in GitHub Desktop.
Save magnetikonline/a00d4b81745ba81363b5d4c8d010ce93 to your computer and use it in GitHub Desktop.
JavaScript OO class / object inheritance techniques.

JavaScript object inheritance techniques

Via Object.create()

function Shape(x,y) {

	this.x = x;
	this.y = y;
}

Shape.prototype.identify = function() {

	console.info('I am a shape');
};

Shape.prototype.move = function(x,y) {

	this.x += x;
	this.y += y;
	console.info('Shape moved');
};

function Rectangle(x,y) {

	// call super constructor
	Shape.call(this,x,y);
	this.identify();
}

Rectangle.prototype = Object.create(Shape.prototype);

var rect = new Rectangle(5,10);
rect.move(-1,2);
console.log(rect.x,rect.y);

Via ES6 class

'use strict';

class Shape {

	constructor(x,y) {

		this.x = x;
		this.y = y;
	}

	identify() {

		console.info('I am a shape');
	}

	move(x,y) {

		this.x += x;
		this.y += y;
		console.log('Shape moved');
	}
}

class Rectangle extends Shape {

	constructor(x,y) {

		// call super constructor
		super(x,y);
		super.identify();
	}
}

var rect = new Rectangle(5,10);
rect.move(-1,2);
console.log(rect.x,rect.y);

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment