The inheritance implementation of mootools-like class(but slightly different) for JavaScript modules.
Before anything taking its part, you should install node and cortex.
cortex install class --save
var Class = require('class');
var Person = Class({
initialize: function(name){
this.name = name;
},
study: function(n){
console.log('study')
},
selfIntro: function(){
console.log('My name is ' + this.name);
}
});
var Female = Class({
Extends: Person,
initialize: function(name, gender){
Person.call(name);
this.gender = gender;
}
});
var Lily = new Femail('Lily', 'female');
Lily.selfIntro(); // My name is Lily.
var SuperClass = Class({
foo: function(){
console.log('foo')
}
});
var MyClass = Class({
Extends: SuperClass
});
var SubClass = Class({
Extends: MyClass
})
new SubClass().foo(); // foo
Extending SuperClass
will retain the prototype chain, even if the current constructor has gone through a series of inheritance.
var MyClass = Class({
Implements: 'events'
})
Use the Implements
property to mixin a bunch of utility methods. The methods impleme
Implements: 'events' // implements events
Implements: 'events attrs' // events and attributes
Implements: constructor
Implements: constructor.prototype
Implements: singletonObject
Implements: [constructor, singleton, 'events']
If you Implements: 'events'
, the constructor will be an EventEmitter and will has exactly the same APIs as nodejs's.
var MyClass = Class({
Implements: 'attrs',
initialize: function(options){
this.set(options);
}
}, {
foo: {
value: 1,
validator: function(v){
return typeof v === 'number';
}
},
bar: {
getter: function(v){
return v < 10 ? 10 : v;
}
}
});
var obj = new MyClass({
foo: '3',
bar: 7
});
obj.get('foo'); // 1, '3' fails against the validator
obj.get('bar'); // 10
obj.set('foo', 100);
obj.get('foo'); // 100
After implementing 'attrs'
, the prototype of the constructor will have 4 methods:
- addAttr: add an attribute description
- get: get the value by key
- set: set a key or list of keys
- removeAttr: remove an attribute
See attributes
for more details about 'attrs'
.
Creates a new class.
var MyClass = Class(definition, attributes);
Returns the constructor of the newly created class.
Inherits from a super class.
Mixin utility methods.
Define the properties of the prototype.