JSFiddle - React, Tailwind, and code Playground

by Jennifer Piccione

JavaScript

// Mixin by extension
//
// extend() function will copy properties from
// a source object to the destination
function extend(destination, source) {
    for (var k in source) {
        if (source.hasOwnProperty(k)) {
            destination[k] = source[k];
        }
    }
    return destination;
}

// Functional Mixins
//
// the myMixins function will apply its properties 
// onto the scope passed in by "call" or "apply"
var myMixins = function () {

    // note use of "this" to apply within scope
    this.newMethod = function () {
        return this.id;
    };

    this.otherMethod = function () {};

    return this;

}

var PrimaryObject = function (id) {
    this.getId = function () {
        return id;
    };
}

myMixins.call(PrimaryObject.prototype);

console.log(new PrimaryObject());

// Closure Mixins
//
// By wrapping the mixin function in a closure
// we define the mixin functions once, improving performance
var myMixins = (function () {

    // note: no longer using "this" to define the new methods
    // instead we return a function which defines the methods,
    // referencing the private (closed over) methods, which are defined once
    var newMethod = function () {
        return this.id;
    };

    var otherMethod = function () {};

    return function () {
        this.newMethod = newMethod;
        this.otherMethod = otherMethod;
        return this;
    };

})();

var PrimaryObject = function (id) {
    this.getId = function () {
        return id;
    };
}

myMixins.call(PrimaryObject.prototype);

console.log(new PrimaryObject());