symbol.js 1015 B

123456789101112131415161718192021222324252627282930313233343536
  1. const _symbols = [];
  2. const __internalMark__ = {};
  3. class HiddenSymbol {
  4. constructor(target) {
  5. Object.defineProperties(this, {
  6. target: {
  7. enumerable: false,
  8. writable: false,
  9. configurable: false,
  10. value: target,
  11. },
  12. });
  13. }
  14. }
  15. export class InternalSymbol extends HiddenSymbol {
  16. constructor(target, __mark__) {
  17. if (__mark__ !== __internalMark__) {
  18. throw new TypeError('InternalSymbol cannot be constructed with new operator');
  19. }
  20. super(target);
  21. }
  22. static for(target) {
  23. for (let i = 0, len = _symbols.length; i < len; i++) {
  24. if (_symbols[i].target === target) {
  25. return _symbols[i].instance;
  26. }
  27. }
  28. const symbol = new InternalSymbol(target, __internalMark__);
  29. _symbols.push({
  30. target,
  31. instance: symbol,
  32. });
  33. return symbol;
  34. }
  35. }
  36. export default InternalSymbol;