Skip to content

Instantly share code, notes, and snippets.

@rahulkmr
Last active April 10, 2017 10:06
Show Gist options
  • Save rahulkmr/9482010 to your computer and use it in GitHub Desktop.
Save rahulkmr/9482010 to your computer and use it in GitHub Desktop.
// Helper for implementing mixins.
function mixin(dest) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var prop in source) {
if (!dest[prop]) {
dest[prop] = source[prop];
}
}
}
}
// Template for writing a basic class
// Here the constructor takes the arguments `firstName` and `lastName`
function Person(firstName, lastName) {
// createdAt is analogous to private variable
var createdAt = new Date();
// These are public.
this.firstName = firstName;
this.lastName = lastName;
// The variable `createdAt` can't be accessed without this accessor
this.createdAt = function() {
return createdAt;
}
}
// Your usual method.
Person.prototype.getName = function() {
return this.lastName + ", " + this.firstName;
}
// This is a mixin
function Serializable() {}
Serializable.prototype = {
serialize: function() {
print("Serializing " + this.getName());
}
}
// Now Person is Serializable. The properties of mixin Serializable are
// mixed into person.
mixin(Person.prototype, Serializable.prototype);
// This is an example of inheritance.
function User(firstName, lastName, password) {
this.password = password;
// JS doesn't have a super() way of calling parent constructor.
// This will just call constructor. The prototype will have to be inherited later.
Person.call(this, firstName, lastName);
}
// Inherit from Person
User.prototype = Object.create(Person.prototype);
// Add method unique to Person.
User.prototype.getPassword = function() {
return this.password;
}
// Override method.
User.prototype.getName = function() {
// We aren't actually overriding anything but just calling super method.
return Person.prototype.getName.call(this);
}
// Another mixin.
// Mixins can be object literals(and generally are).
var Authorizable = {
authorize: function() {
print("Authorizing " + this.getName());
}
}
mixin(User.prototype, Authorizable);
// Demo
var user = new User("Rahul", "Kumar", "test");
print(user.getName());
print(user.createdAt());
user.serialize();
user.authorize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment