Skip to content

Instantly share code, notes, and snippets.

@pawelqbera
Last active October 17, 2015 21:33
Show Gist options
  • Save pawelqbera/53f72f93675578ddd72e to your computer and use it in GitHub Desktop.
Save pawelqbera/53f72f93675578ddd72e to your computer and use it in GitHub Desktop.
Classical Inheritance in Object Oriented JavaScript
/**
* (Pseudo)Classical Inheritance in JavaScript
*/
// Helpers and polyfills
/**
* Copies object's prototype properties
* to another object's prototype
*/
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
/**
* Polyfill for Object.create()
*/
if ( typeof Object.create !== 'function' ) {
Object.create = function(o, props) {
function F() {}
F.prototype = o;
result = new F();
if ( typeof(props) === "object" ) {
for (var prop in props) {
if (props.hasOwnProperty((prop))) {
result[prop] = props[prop].value;
}
}
}
return result;
};
}
// SuperClass
var Orb = function(name) {
this.name = name;
};
Orb.prototype.spin = function() {
console.log(this.name + ' is spinning around!');
};
Orb.prototype.circle = function() {
console.log(this.name + ' is circling around the Sun!');
};
// Planet
var Planet = function(name) {
//this.name = name;
Planet.super_.call(this, name);
};
inherits(Planet, Orb);
// Moon Class
var Moon = function(name, planet) {
//this.name = name;
Moon.super_.call(this, name);
this.planetName = planet.name;
};
inherits(Moon, Planet);
Moon.prototype.circle = function() {
console.log(this.name + ' is circling around the ' + this.planetName);
};
// Usage
var earth = new Planet("Earth");
var moon = new Moon("Moon", earth);
earth.spin();
earth.circle();
moon.spin();
moon.circle();
var saturn = new Planet("Saturn");
var titan = new Moon("Titan", saturn);
titan.spin();
titan.circle();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment