Last active
December 26, 2015 08:59
-
-
Save ducin/7126431 to your computer and use it in GitHub Desktop.
JavaScript class implementation (with example PersonClass declaration)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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