This module is in active development, and still in beta, do not use in production.... yet
A Multiple composable inheritance module for js
def-type is an npm module that allows you to easily define Objects and classes that can inherit from a single parent object by adding it to the prototype chain of the defined Object/Class (via the 'extends' directive) or from multiple objects or "classes" (via 'merges' directive), which also lets you to choose which attributes you merge(copy). It also allows you to work with true shared privacy with almost the same syntax.
npm install def-type --save
def = require'def-type'
Class definition (All attributes not defined in the constructor will live in the prototype obj)
Character = defClass:# some code:# some codePlayer = defClassextends: Character # It will add the Character.prototype to the Player.prototype chain:Player_superconstructorcall@ # Available when extending but not when merging.: -># some code: -># some codeplyr1 = 'zaggen'
Object definition (Pretty much the same as defining an object literal)
enemyBoss = defObjectextends: Character # It sets Character.prototype as the prototype of the enemyBoss obj: -># some code: -># some code
Mixin definition This is an alias of def.Object. It is recommended that you name your objects with the Traits suffix when they are supposed to be merged into other objects/classes, and when your Traits Object needs to merge/mix in some functionality/properties from other objects/classes you use def.Mixin. This way we get a performance boost when defining simple traits (What pretty much the rest of the js world calls a mixin), and we only use this term to objects that are supposed to be merged/mixed in but they also merge/mix in other objects/mixins/classes.
# This is a traits ObjectencryptingTraits =: -># some code: -># some code# This is a Mixin Traits ObjectaccountTraits = defMixinmerge: encryptingTraits:# some code:# some code
Module definition This is another alias for def.Object, it is recommended for npm style modules. So you can define functionality packed in a module(which is a regular object) that needs to expose a small public API.
injector = defModule ->=# some code= -># some code# Private fnsimport =# some code=#some code
Here is a working example using this option: commonjs-injector
Usage with multiple inheritance and defined constructor
You can inherit from multiple "Classes" or objects, or a mixture of both.
Admin = defClassmerges: accountTraits'logIn''logOut'User# here User is a class:@privileges = 'all': -># Some Code: -># Some Codezaggen = 'zaggen'
Please note that 'merges' copies the attributes or references to the defined item, so any change in the parents won't be reflected in the defined item.
Abstract definition Sometimes you want to define an npm like module or a Class that is not supposed to be used directly, but to be extended and it doesn't makes much sense as a Traits obj. You can define that kind of object or class with def.Abstract. When you set a constructor it internally calls def.Class, and when you don't it used def.Object, there is no special safety mechanism for preventing direct instantiation or usage, is up to you as a programmer to follow this convention.
FrontEndController = defAbstract: -># some code: -># some code: -># some code# Here user controller is a FrontEndController and has accountTraitsUserController = defClassextends: FrontEndControllermerges: accountTraits: ->UserController_supercall@
Usage with real private methods and attrs(static/shared)
You can get true privacy when passing a lambda instead of an object, in this anonymous fn you will define your public attrs as instance members of that fn, and your private attributes as local variables, the nice thing here is a that all your public functions will have access to the private stuff (This is a closure that is executed internally) and you can define your private variables at the bottom like in ruby, which is hard to do in cs because we only have fn expressions so we don't get hoisted fns... anyways, you can use private properties too (data) but this data will be shared across all instances of the class, so be aware of that, its usefull for objects, but not that much for classes. You can use weakMaps to accomplish this but that is not something def-type will do for you, additionally bare in mind that if you add public functions later, this fns can't access the previously defined private properties, because they will be out of scope, so monkey patching is not possible, also you can't inherit private members. Is probably better to use the underscore convention for private attrs in most cases, but sometimes you really want this behavior, so here it is.
Admin = defClass -># private properties have to be defined at the top in csinstanceNumber = 0 # Static variable, will be shared accross all instances# Public=instanceNumber++= -> return instanceNumber=dbQuery'delete'id=dbQuery'modify'iddata# Private Methods=# Some Codezaggen = 'zaggen'zaggendeleteUser5 # WorkszaggendbQuery'delete'5 # Won't work
Usage with real private methods and attrs(shared) and accessors
user = defObject ->name = 'John'lastName = 'Doe'@accessors = 'fullName'# Add the names of the properties that you want to define as accessors@fullName =: -> " ":nameParts = fullNamesplit' 'name = nameParts0lastName = nameParts1consolelog userfullName # Logs 'John Doe'user.fullName = 'Max Payne' # Sets the private name and lastName variables with the value providedconsolelog userfullName # Logs 'Max Payne'
- Set another object/Class as the prototype of the defined element (Using extends).
- Merge properties from other objects/classes into the defined element (Using merges).
- You have composite options, meaning you can pick which attributes you merge and even set the context of methods to their original objects.
_superobject is created when the defined type is being extended or merged, it will contain all of the inherited (extended and merged) methods into it. This is useful when you want to override an inherited parent method but you still want to have access to the original functionality. To avoid getting the wrong super, you must reference the defined object or class instead of using
this. Methods that makes changes to instance members should be called using
.call(this, arg1, arg2)or
- You can define 'classes' very easy, and extend them with out ,manually adding the parent class prototype to the currently defined class and setting back the original constructor, or adding methods to the prototype one by one.
When you pass an options array after the object to be merge, e.g:
You can specify which properties you merge into the defined obj/class, by combining the property names you want to
add or exclude from the mixin/class and/or a few optional flags (
- This are the options in details
['attr1', 'attr2']Will only include those selected attributes from the corresponding object
['~publicMethod']This functionality will be deprecated in the next update Delegate; Will only include those selected method and it will bind its context to the original object/Class.
['!', 'privateAttr']Will exclude the selected attr, and include the rest
['!']Will exclude all attributes. Only useful for debugging purposes
['*']Will include all attributes. By default if you don't provide a confArray there is no need to explicitly say to include all attributes, but if you like to be explicit here is the option.
def = require'def-type'hardObjTraits =colliding: false: -># Detects if object is colliding with other hardObjsmovableTraits =x: 0y: 0:# Moves from current x,y to the new pos in the given timespriteTraits =:# Sets sprite to the specified bitmap: -># Updates sprite# A Mixin is an object that mixes/merges in functionality from other objects and is supposed# to be merged into another object or class and not to be used directly.gameCharacterTraits = defMixinmerges: movableTraitsspriteTraitshardObjTraits_exp: 0:@_increaseExpnewExp # Private Method Call# Lvl up based on exp: @_exp += newExp# A defined Object is supposed to be used as it is, like a customized instance of Object.hero = defObjectmerges: gameCharacterTraitsname: 'Zaggen'stats:agi: 23def: 45str: 99heromove100200100 # Moves the hero to position (100,200) in 100 millisecondskillableTraits =_hp: 100:#Set hp to 0, and show dead animationPlayer = defClassmerges: gameCharacterTraits'~lvlUp'killableTraits'kill':@msg = " is ready to kill some goblins!": ->consolelog @msg: ->Player_superkillcall@ # Unless kill is a pure fn with no side effects, it should be called using call or applyconsolelog 'Game Over'zaggen = 'Zaggen'zaggensayMsg # Outputs "Zaggen is ready to kill some goblins!"zaggenlvlUp100 #Increases exp, and if enough it'll lvl up the playerzaggenmove154010 # Moves the character to position (15,40) in 10 milliseconds
Bugs, questions, ideas?
Hell, yeah, just open an issue and i'll try to answer ASAP. I'll appreciate any bug report with a proper way to reproduce it.