JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 244
  • Score
    100M100P100Q82459F
  • License MIT

a tiny util to mix functions and properties into a prototype

Package Exports

  • mixes

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (mixes) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

mixes

stable

A minimal util to mixin functions and properties. This helps reduce the boilerplate and repetition of MyClass.prototype and Object.defineProperty.

//mixin some stuff to MyClass.prototype
require('mixes')(MyClass, {

    //mixin functions
    foo: function(a, b) {
        return a + b
    },
    
    //mixin an object for Object.defineProperty
    bar: {
        get: function() {
            return "boop"
        }
    }	
})

Then, you can use them as expected:

var m = new MyClass()
m.foo(a, b)
console.log( m.bar )

It also allows you to create collections of mixins easily:

var mixes = require('mixes')

function Dagger() {
}

mixes(Dagger, require('./mixins/item'))
mixes(Dagger, require('./mixins/weapon'))

motivation

The earlier code would look like this in pure JS, and tends to bloat as you add more functions and properties.

MyClass.prototype.foo = function(a, b) {
    return a + b
}

Object.defineProperty(MyClass.prototype, "bar", {
    enumerable: true,
    configurable: true,
    get: function() {
        return "boop"
    }
})

This is also nicer than Blah.prototype = { ... } since it doesn't destroy your prototype chain (i.e. if you're inheriting from a base class).

Usage

NPM

mixes(ctor, entries)

For a constructor function or object with prototype, mixes in the given functions and properties. entries is an object with named functions or objects.

When an object is encountered, it is treated as a property and injected with Object.defineProperty. By default, configurable and enumerable are true if not specified, although you can override it like so:

mixes(Foo, {
    bar: {
        enumerable: true,
        writable: false,
        value: 5
    }
})

Other types (numbers, strings, etc) are ignored.

mixes.mix(obj, entries)

The same as above, but operates on any object as opposed to an object's prototype.

License

MIT, see LICENSE.md for details.