admin管理员组文章数量:1388105
Could anyone remend 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 wele as well.
Thanks.
Could anyone remend 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 wele as well.
Thanks.
Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Aug 8, 2011 at 2:23 Alex HeydAlex Heyd 1,3231 gold badge10 silver badges17 bronze badges5 Answers
Reset to default 3I 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.
Two papers that do describe library agnostic pure function based Mixin and Trait approaches for JavaScript are A fresh look at JavaScript Mixins by Angus Croll from May 2011 and The many talents of JavaScript for generalizing Role Oriented Programming approaches like Traits and Mixins from April 2014.
so long
Appendix I
please see also:
- stackoverflow. :: Traits in javascript
- stackoverflow. :: How to use mixins properly in Javascript
Appendix II
Since from time to time I'm apparently fiddle with this matter I wan't to add some final thoughts to it ...
The library agnostic approach without too much glue code (as mentioned above) does work only for very fine grained posable units of behavioral reuse. Thus, as long as one does not run into more than 1 or 2 easily resolvable conflicts, patterns based on e.g. Angus Croll's Flight Mixins are the path to follow.
If it es to real traits, there has to be an abstraction level to it. This layer (e.g. provided as some sort of syntactic sugar like a DSL) needs to hide the plexity e.g. of posing traits from traits or of conflict resolution at a traits apply time (when a trait's behavior gets applied to an object/type).
By now there are 3 examples at SO that from my perspective provide exactly what the OP did ask for …
Any real world examples would be wele as well.
- stackoverflow. :: Compostions and mixins in JS
- stackoverflow. :: Mixins for ES6 classes, transpiled with babel
- stackoverflow. :: Refactoring legacy mixin-based class hierarchies
- stackoverflow. :: Multiple inheritance using classes
You can use function to implement traits without a library.
See working example Traits + Inheritance
Thanks to dbarbeau
// Usage __traits(TargetClass, Trait1, Trait2, ...);
// Mix multiple definitions as traits. Properties will be overwritten if names are duplicating.
function __traits(mixtureTarget) {
for(var a=1; a < arguments.length; ++a) {
var mixin = arguments[a];
for (var p in mixin){ if (mixin.hasOwnProperty(p)){ mixtureTarget[p] = mixin[p]; } };
Object.getOwnPropertyNames(mixin.prototype).forEach( function(name) {
mixtureTarget.prototype[name] = mixin.prototype[name];
});
};
};
there is simple and lightweight a package in npm for this. you can check it here, it really made trait from PHP feature easily get implemented on Javascript.
https://github./regs37/trait.js
// create a simple trait that you want to be reusable
const MyTrait = trait({
sampleTrait: function(){
return "trait";
}
})
// lets have a sample class User
class User {
}
// we will inherit the trait to the User Class
MyTrait.in(User);
// sample instance of the user
let user = new User();
// try to call he trait we have inherited
console.log(user.sampleTrait()); // trait
<script src="https://unpkg./[email protected]/build/trait.min.js"></script>
本文标签: Javascript Traits Pattern ResourcesStack Overflow
版权声明:本文标题:Javascript Traits Pattern Resources - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744526546a2610777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论