auto-bind.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. var copy = require('es5-ext/object/copy')
  3. , normalizeOptions = require('es5-ext/object/normalize-options')
  4. , ensureCallable = require('es5-ext/object/valid-callable')
  5. , map = require('es5-ext/object/map')
  6. , callable = require('es5-ext/object/valid-callable')
  7. , validValue = require('es5-ext/object/valid-value')
  8. , bind = Function.prototype.bind, defineProperty = Object.defineProperty
  9. , hasOwnProperty = Object.prototype.hasOwnProperty
  10. , define;
  11. define = function (name, desc, options) {
  12. var value = validValue(desc) && callable(desc.value), dgs;
  13. dgs = copy(desc);
  14. delete dgs.writable;
  15. delete dgs.value;
  16. dgs.get = function () {
  17. if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
  18. desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
  19. defineProperty(this, name, desc);
  20. return this[name];
  21. };
  22. return dgs;
  23. };
  24. module.exports = function (props/*, options*/) {
  25. var options = normalizeOptions(arguments[1]);
  26. if (options.resolveContext != null) ensureCallable(options.resolveContext);
  27. return map(props, function (desc, name) { return define(name, desc, options); });
  28. };