Classes are used to simplify JavaScript constructor creation. Both $.Controller and $.Model extend $.Class.
To create a Class class of your own, call $.Class.extend with the:
- name of the class which can be used for introspection,
- classProperties that are attached directly to the constructor, and
- instance prototypeProperties.
$.Class sets up the prototype chain so subclasses created with extend can be further extended and sub-classed as far as you like:
$.Class("Note",{
init : function(){},
author : function(){ ... },
coordinates : function(){ ... },
allowedToEdit: function(account) {
return true;
}
});
Note('PrivateNote',{
allowedToEdit: function(account) {
return account.owns(this);
}
})
Brief aside on super
. JavaScript does not provide a way to call super -the function of the same name higher on the prototype chain. However, you can either do it by using the [super] plugin, or by explicitly calling it like:
var SecureNote = PrivateNote({
allowedToEdit: function(account) {
return PrivateNote.prototype.allowedToEdit.call(this, account) &&
this.isSecure();
}
})
When a class instance is created, $.Class creates the instance and calls $.Class.prototype.init with the arguments passed to new Class(...)
.
Note = $.Class({
init : function(text) {
this.text = text
},
read : function(){
console.log(this.text);
}
})
var note = new Note("Hello World");
note.read()
Brief aside on init. $.Class actually calls $.Class.prototype.setup
before init. setup
can be used to change the arguments passed to init.
Models are central to any application. They contain data and logic surrounding it. You extend $.Model with your domain specific methods and $.Model provides a set of methods for managing changes.
To create a Model class, call $.Model with the:
- name of the class,
- optional classProperties that are attached directly to the constructor, and
- prototype instance properties.
When a $.Class is extended, it calls .init with the arguments to .extend. This is useful for adding setup code.
$.Class("MyBase",{ defaults : { foo: 'bar' } },{})
MyBase("Inheriting",{ defaults : { newProp : 'newVal' } },{}
Inheriting.defaults -> {foo: 'bar', 'newProp': 'newVal'}
constructor/initialize