redefine.js 1.6 KB

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