DefineOwnProperty.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
  4. if ($defineProperty) {
  5. try {
  6. $defineProperty({}, 'a', { value: 1 });
  7. } catch (e) {
  8. // IE 8 has a broken defineProperty
  9. $defineProperty = null;
  10. }
  11. }
  12. // node v0.6 has a bug where array lengths can be Set but not Defined
  13. var hasArrayLengthDefineBug = Object.defineProperty && Object.defineProperty([], 'length', { value: 1 }).length === 0;
  14. // eslint-disable-next-line global-require
  15. var isArray = hasArrayLengthDefineBug && require('../2020/IsArray'); // this does not depend on any other AOs.
  16. var callBound = require('call-bind/callBound');
  17. var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
  18. // eslint-disable-next-line max-params
  19. module.exports = function DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, desc) {
  20. if (!$defineProperty) {
  21. if (!IsDataDescriptor(desc)) {
  22. // ES3 does not support getters/setters
  23. return false;
  24. }
  25. if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) {
  26. return false;
  27. }
  28. // fallback for ES3
  29. if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) {
  30. // a non-enumerable existing property
  31. return false;
  32. }
  33. // property does not exist at all, or exists but is enumerable
  34. var V = desc['[[Value]]'];
  35. // eslint-disable-next-line no-param-reassign
  36. O[P] = V; // will use [[Define]]
  37. return SameValue(O[P], V);
  38. }
  39. if (
  40. hasArrayLengthDefineBug
  41. && P === 'length'
  42. && '[[Value]]' in desc
  43. && isArray(O)
  44. && O.length !== desc['[[Value]]']
  45. ) {
  46. // eslint-disable-next-line no-param-reassign
  47. O.length = desc['[[Value]]'];
  48. return O.length === desc['[[Value]]'];
  49. }
  50. $defineProperty(O, P, FromPropertyDescriptor(desc));
  51. return true;
  52. };