auto-bind.js 1.2 KB

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