Created
April 21, 2012 16:51
-
-
Save raroni/2438322 to your computer and use it in GitHub Desktop.
Classico - mini lib for creating classes in JS/Coffeescript
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
"use strict" | |
# Classico lib - go down for examples | |
Classico = {} | |
Classico.prototype = | |
super: (propertyName) -> | |
Object.getPrototypeOf(Object.getPrototypeOf(@))[propertyName].call @ | |
Classico.include = (hash) -> | |
for key, value of hash | |
match = key.match(/^get([A-Z]{1}.*)$/) | |
if match && typeof(value) == 'function' | |
propertyName = match[1].replace /.{1}/, (v) -> v.toLowerCase() | |
Object.defineProperty this.prototype, propertyName, { get: value } | |
else | |
this.prototype[key] = hash[key] | |
Classico.extend = (hash) -> | |
klass = -> | |
klass.prototype = Object.create this.prototype | |
includeModules = hash.include | |
delete hash.include | |
Classico.include.call klass, value for value in includeModules if includeModules | |
Classico.include.call klass, hash | |
klass.extend = this.extend | |
klass.create = -> | |
object = Object.create klass.prototype | |
object.constructor.apply(object, arguments) if object.constructor | |
object.constructor = klass | |
object | |
klass | |
#################################################################################### | |
# EXAMPLES | |
# Defining a module | |
Seeing = | |
getCanSee: -> true | |
# Defining a super class | |
Person = Classico.extend | |
include: [Seeing] | |
constructor: (@name, @age) -> | |
identify: -> | |
'My name is ' + this.name + ', I am a ' + this.age + ' yearold ' + this.sex + '!' | |
getSex: -> | |
if this.sexCode == 0 then 'male' else 'female' | |
# Subclassing Person | |
Man = Person.extend | |
sexCode: 0 | |
size: -> 'big' | |
# Subclassing Man | |
Boy = Man.extend | |
size: -> | |
@super('size') + ', at least for my age' | |
# Creating instance of Boy | |
johnny = Boy.create 'Johnny', 25 | |
# Now for testing that everything works. | |
# The classes talk nicely together | |
console.log(johnny.identify() == 'My name is Johnny, I am a 25 yearold male!') | |
# Instance operator works as expected | |
console.log(johnny instanceof Man) | |
console.log(johnny instanceof Person) | |
# getSex was converted to sex propery | |
console.log(johnny.sex == 'male') | |
console.log(johnny.constructor == Boy) | |
# canSee is from an included module (Seeing) - also using a getter btw | |
console.log(johnny.canSee) | |
# Object.getPrototypeOf works as expected | |
console.log(Object.getPrototypeOf(johnny) == Boy.prototype) | |
# Using super | |
console.log(johnny.size() == 'big, at least for my age') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment