redefine.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var global = require('../internals/global');
  2. var isCallable = require('../internals/is-callable');
  3. var hasOwn = require('../internals/has-own-property');
  4. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  5. var setGlobal = require('../internals/set-global');
  6. var inspectSource = require('../internals/inspect-source');
  7. var InternalStateModule = require('../internals/internal-state');
  8. var CONFIGURABLE_FUNCTION_NAME = require('../internals/function-name').CONFIGURABLE;
  9. var getInternalState = InternalStateModule.get;
  10. var enforceInternalState = InternalStateModule.enforce;
  11. var TEMPLATE = String(String).split('String');
  12. (module.exports = function (O, key, value, options) {
  13. var unsafe = options ? !!options.unsafe : false;
  14. var simple = options ? !!options.enumerable : false;
  15. var noTargetGet = options ? !!options.noTargetGet : false;
  16. var name = options && options.name !== undefined ? options.name : key;
  17. var state;
  18. if (isCallable(value)) {
  19. if (String(name).slice(0, 7) === 'Symbol(') {
  20. name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
  21. }
  22. if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
  23. createNonEnumerableProperty(value, 'name', name);
  24. }
  25. state = enforceInternalState(value);
  26. if (!state.source) {
  27. state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
  28. }
  29. }
  30. if (O === global) {
  31. if (simple) O[key] = value;
  32. else setGlobal(key, value);
  33. return;
  34. } else if (!unsafe) {
  35. delete O[key];
  36. } else if (!noTargetGet && O[key]) {
  37. simple = true;
  38. }
  39. if (simple) O[key] = value;
  40. else createNonEnumerableProperty(O, key, value);
  41. // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
  42. })(Function.prototype, 'toString', function toString() {
  43. return isCallable(this) && getInternalState(this).source || inspectSource(this);
  44. });