auto-bind.js 919 B

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