Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Traits Pattern Resources

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.

like image 946
Alex Heyd Avatar asked Jun 22 '26 20:06

Alex Heyd


2 Answers

I would suggest something simple, along the lines of:

  1. Let traits be defined as standard JavaScript objects.

    var equalsTrait = {
        eq: function(obj) {
            return this == obj
        },
        neq: function(obj) {
            return ! this.eq(obj)
        }
    };
    
  2. 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];
            }
        }
    }
    
  3. Profit!

like image 159
aroth Avatar answered Jun 24 '26 10:06

aroth


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.

like image 43
widged Avatar answered Jun 24 '26 09:06

widged