UNPKG

instance-mixer

Version:

Helps with adding methods to some instance. Best used with util.inherits.

66 lines (53 loc) 1.47 kB
'use strict'; /** * Expose `InstanceMixer`. */ module.exports = InstanceMixer; /** * InstanceMixer helps with adding methods to some instance. Best used with * util.inherits. * * @constructor * @api public */ function InstanceMixer(mixins, options){ if (!(this instanceof InstanceMixer)) { return new InstanceMixer(mixins, options); } mixins = mixins || []; options = options || {}; this.addMixins(mixins, options); } /** * Adds mixins to the instance. * * @param {Array} mixins * @param {Object} options * @api public */ InstanceMixer.prototype.addMixins = function(mixins, options){ for (var i = 0, length = mixins.length; i < length; i++) { this.addMixin(mixins[i], options); } }; /** * Adds a mixin to the instance. Mixin may contain an `init` {Function} to be * called when creating the instance. * * @param {Object} mixin * @param {Object} options * @api public */ InstanceMixer.prototype.addMixin = function(mixin, options){ for (var key in mixin) { if (key === 'init' && typeof mixin.init === 'function') { mixin.init.call(this, options); } else if (mixin.hasOwnProperty(key)) { Object.defineProperty( this, key, Object.getOwnPropertyDescriptor(mixin, key) ); } } };