Skip to content

Instantly share code, notes, and snippets.

@ducin
Last active December 26, 2015 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducin/7126431 to your computer and use it in GitHub Desktop.
Save ducin/7126431 to your computer and use it in GitHub Desktop.
JavaScript class implementation (with example PersonClass declaration)
var Class = function(base){
if (typeof base.construct !== "function")
throw new TypeError("class definition has to define 'construct' function");
return function() {
// copy all methods
for (var prop in base) {
if (base.hasOwnProperty(prop) && base[prop] !== base.construct) {
this[prop] = base[prop];
}
}
// call the constructor
var args = Array.prototype.slice.call(arguments);
base.construct.apply(this, args);
}
};
var personDefinition = {
construct: function construct(firstname, lastname) {
this.firstname = firstname || this.firstname;
this.lastname = lastname || this.lastname;
},
firstname: 'John',
lastname: 'Doe',
getFullName: function() {
return this.firstname + ' ' + this.lastname;
}
};
var Person = Class(personDefinition);
var person1 = new Person("John", "Lennon");
var person2 = new Person("Paul", "McCartney");
var person3 = new Person("Saint");
var person4 = new Person();
person1 instanceof Person; // true
person1.getFullName(); // 'John Lennon'
person2 instanceof Person; // true
person2.getFullName(); // 'Paul McCartney'
person3 instanceof Person; // true
person3.getFullName(); // 'Saint Doe'
person4 instanceof Person; // true
person4.getFullName(); // 'John Doe'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment