-
Notifications
You must be signed in to change notification settings - Fork 5
Space.Object
Dominik Guzei edited this page Jan 19, 2016
·
3 revisions
Space also comes with a simple but powerful inheritance system
that can save you from typing prototype
all the time:
var BaseClass = Space.Object.extend({
dependencies: { lib: 'OtherCode' },
sayHello: function() { this.lib.sayHello(); }
});
var MyClass = BaseClass.extend({
name: '',
sayHello: function() {
BaseClass.prototype.sayHello.call(this);
console.log('I am ' + this.name);
}
});
var instance = MyClass.create({ name: 'Dominik' });
injector.injectInto(instance);
instance.sayHello(); // logs: 'hello!' and 'I am Dominik'
This is also fully compatible with Coffeescript:
class AwesomeClass extends MyClass
dependencies:
prefixes: 'Prefixes'
constructor: (properties) ->
properties.name = "#{@prefixes.random()} #{properties.name}"
# Calls the Space.Object constructor which
# assigns all properties to the instance
super(properties)
prefixes = random: -> 'the amazing' # could return anything
injector.map('Prefixes').to prefixes
instance = AwesomeClass.create({ name: 'Spiderman' });
injector.injectInto instance # provides 'OtherCode' and 'Prefixes'
instance.sayHello() # logs: 'hello!' and 'I am the amazing Spiderman'
As nice little sugar on top of "standard" classical inheritance it also provides an easy way to work with static class methods and properties:
var BaseClass = Space.Object.extend({
dependencies: { lib: 'OtherCode' },
statics: {
getRootClassName: function() {
return 'BaseClass';
}
},
// Return the class prototype
sayHello: function() { this.lib.sayHello() }
});
var MyClass = BaseClass.extend({
sayHello: function() {
// You can also access the super class like this
MyClass.__super__.sayHello.call(this);
// Static properties and methods are copied to sub-classes
console.log('My root is ' + MyClass.getRootClassName());
}
});