es.reflect.set.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var $ = require('../internals/export');
  2. var call = require('../internals/function-call');
  3. var anObject = require('../internals/an-object');
  4. var isObject = require('../internals/is-object');
  5. var isDataDescriptor = require('../internals/is-data-descriptor');
  6. var fails = require('../internals/fails');
  7. var definePropertyModule = require('../internals/object-define-property');
  8. var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
  9. var getPrototypeOf = require('../internals/object-get-prototype-of');
  10. var createPropertyDescriptor = require('../internals/create-property-descriptor');
  11. // `Reflect.set` method
  12. // https://tc39.es/ecma262/#sec-reflect.set
  13. function set(target, propertyKey, V /* , receiver */) {
  14. var receiver = arguments.length < 4 ? target : arguments[3];
  15. var ownDescriptor = getOwnPropertyDescriptorModule.f(anObject(target), propertyKey);
  16. var existingDescriptor, prototype, setter;
  17. if (!ownDescriptor) {
  18. if (isObject(prototype = getPrototypeOf(target))) {
  19. return set(prototype, propertyKey, V, receiver);
  20. }
  21. ownDescriptor = createPropertyDescriptor(0);
  22. }
  23. if (isDataDescriptor(ownDescriptor)) {
  24. if (ownDescriptor.writable === false || !isObject(receiver)) return false;
  25. if (existingDescriptor = getOwnPropertyDescriptorModule.f(receiver, propertyKey)) {
  26. if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false;
  27. existingDescriptor.value = V;
  28. definePropertyModule.f(receiver, propertyKey, existingDescriptor);
  29. } else definePropertyModule.f(receiver, propertyKey, createPropertyDescriptor(0, V));
  30. } else {
  31. setter = ownDescriptor.set;
  32. if (setter === undefined) return false;
  33. call(setter, receiver, V);
  34. } return true;
  35. }
  36. // MS Edge 17-18 Reflect.set allows setting the property to object
  37. // with non-writable property on the prototype
  38. var MS_EDGE_BUG = fails(function () {
  39. var Constructor = function () { /* empty */ };
  40. var object = definePropertyModule.f(new Constructor(), 'a', { configurable: true });
  41. // eslint-disable-next-line es-x/no-reflect -- required for testing
  42. return Reflect.set(Constructor.prototype, 'a', 1, object) !== false;
  43. });
  44. $({ target: 'Reflect', stat: true, forced: MS_EDGE_BUG }, {
  45. set: set
  46. });