PrivateProperty

Weakly references a value to a specified object. May be used to create private fields.

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/391608/744693/PrivateProperty.js

  1. // ==UserScript==
  2. // @name PrivateProperty
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.2
  5. // @description Weakly references a value to a specified object. May be used to create private fields.
  6. // @author Gerrit Höhle
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. /* jshint esversion: 6 */
  11. const PrivateProperty = (() => {
  12. let prototypeFunctions;
  13.  
  14. class PrivateProperty {
  15.  
  16. constructor(initialValue) {
  17. this._weakReferences = new WeakMap();
  18. this._initialValue = initialValue;
  19. }
  20.  
  21. init(object, initialValueSpecific = this._initialValue) {
  22. const value = (typeof initialValueSpecific === "function") ? initialValueSpecific() : initialValueSpecific;
  23. this._weakReferences.delete(object);
  24. this._weakReferences.set(object, {
  25. initialValue: initialValueSpecific,
  26. value: value
  27. });
  28. return this;
  29. }
  30.  
  31. has(object) {
  32. return this._weakReferences.has(object);
  33. }
  34.  
  35. get(object) {
  36. const data = this._weakReferences.get(object);
  37. if (data) {
  38. return data.value;
  39. }
  40. }
  41.  
  42. set(object, value) {
  43. const data = this._weakReferences.get(object) || {
  44. initialValue: this._initialValue
  45. };
  46. data.value = value;
  47. this._weakReferences.set(object, data);
  48. }
  49.  
  50. getInitialValue(object) {
  51. const data = this._weakReferences.get(object);
  52. return data ? data.initialValue : this._initialValue;
  53. }
  54.  
  55. getOrCompute(object, fnc) {
  56. let data = this._weakReferences.get(object);
  57. if (!data) {
  58. data = {
  59. initialValue: this._initialValue,
  60. value: fnc()
  61. };
  62. this._weakReferences.set(object, data);
  63. }
  64. return data.value;
  65. }
  66.  
  67. for(object) {
  68. const bound = prototypeFunctions.map(([propName, fnc]) => ({ [propName]: fnc.bind(this, object) }));
  69. return Object.assign({}, ...bound);
  70. }
  71. }
  72.  
  73. prototypeFunctions = Object.getOwnPropertyNames(PrivateProperty.prototype)
  74. .filter(propName => typeof PrivateProperty.prototype[propName] === "function")
  75. .filter(propName => propName !== "constructor")
  76. .filter(propName => propName !== "for")
  77. .map(propName => ([ [propName], PrivateProperty.prototype[propName] ]));
  78.  
  79. return PrivateProperty;
  80. })();