Could anyone recommend good resources for using traits in javascript? After some searching I mainly find articles about libraries that provide traits functionality, but I was curious about best practices on how to implement traits without a library.
I came across this post on SO, are there any other approaches? Traits in javascript
Any real world examples would be welcome as well.
Thanks.
I would suggest something simple, along the lines of:
Let traits be defined as standard JavaScript objects.
var equalsTrait = {
eq: function(obj) {
return this == obj
},
neq: function(obj) {
return ! this.eq(obj)
}
};
Write a function to extend a given class with your traits (and bind it to a sensible location in the global scope):
window.Traits = {};
Traits.addToClass = function(traits, cls) {
for (var key in traits) {
if (cls.prototype[key]) {
alert("Class " + cls + " already has a method named " + key + "!");
}
else {
cls.prototype[key] = traits[key];
}
}
}
Profit!
Some (limited) information about traits in the trait.js library
Not about Javascript, but a good paper about inheritance systems and traits "Traits: A Mechanism for Fine-grained Reuse". A description of implementation details can be found in "Applying Traits to the Smalltalk Collection Hierarchy". More papers of this type listed on this page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With