Skip to content

Instantly share code, notes, and snippets.

@HenriqueLimas
Last active August 29, 2015 14:17
Show Gist options
  • Save HenriqueLimas/aadb20051ccc8335f790 to your computer and use it in GitHub Desktop.
Save HenriqueLimas/aadb20051ccc8335f790 to your computer and use it in GitHub Desktop.
Inheritance in Javascript.
(function(window) {
window.ClassJS = {
extend: extend,
clone: clone
};
function extend(subClass, superClass) {
function F() {}
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass._super_ = superClass.prototype;
subClass.constructor = subClass;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
function clone(baseClass) {
function F() {}
F.prototype = baseClass;
return new F;
}
})(window);
/*
* Classical Class inheritance
*/
'use strict';
function SuperClass(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName
this.jedi = false;
}
SuperClass.prototype.getFullName = function() {
console.log('I am from Super ' + this.firstName + ' ' + this.lastName);
};
function ChildClass(firstName, lastName) {
ChildClass._super_.constructor.call(this, firstName, lastName);
this.jedi = true;
}
ClassJS.extend(ChildClass, SuperClass);
ChildClass.prototype.getFullName = function() {
ChildClass._super_.getFullName.call(this);
console.log('I am from child class ' + this.firstName + ' ' + this.lastName + ' Jedi: ' + this.jedi);
};
var child = new ChildClass('Luke', 'Skywalker');
child.getFullName();
/*
* Prototype inheritance.
*/
'use strict';
var SuperClass = {
constructor: function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.jedi = false;
},
getFullName: function() {
console.log('I am from Super ' + this.firstName + ' ' + this.lastName);
}
};
var ChildClass = ClassJS.clone(SuperClass);
ChildClass.constructor = function(firstName, lastName) {
ChildClass.__proto__.constructor(firstName, lastName);
this.jedi = true;
};
ChildClass.getFullName = function() {
ChildClass.__proto__.getFullName();
console.log('I am from child class ' + this.firstName + ' ' + this.lastName + ' Jedi: ' + this.jedi);
};
var child = ClassJS.clone(ChildClass);
child.constructor('Luke' , 'Skywalker');
child.getFullName();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment