Weakly references a value to a specified object. May be used to create private fields.
目前為
此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/391608/744101/PrivateProperty.js
// ==UserScript==
// @name PrivateProperty
// @namespace hoehleg.userscripts.private
// @version 0.1
// @description Weakly references a value to a specified object. May be used to create private fields.
// @author Gerrit Höhle
// @grant none
// ==/UserScript==
/* jshint esversion: 6 */
const PrivateProperty = (() => {
const getOrCreate = (privateProperty, keyObj, defaultData) => {
let data = privateProperty._weakReferences.get(keyObj);
if (!data) {
data = defaultData || { initialValue: privateProperty._initialValue };
privateProperty._weakReferences.set(object, data);
}
return data;
};
return class PrivateProperty {
constructor(initialValue) {
this._weakReferences = new WeakMap();
this._initialValue = initialValue;
}
init(object, initialValueSpecific) {
const data = getOrCreate(this, object);
if (initialValueSpecific) {
data.initialValue = initialValueSpecific;
}
data.value = (typeof data.initialValue === "function") ? data.initialValue() : data.initialValue;
return this;
}
hasValue(object) {
return this._weakReferences.has(object);
}
get(object) {
return this._privateData.get(object);
}
set(object, value) {
this._privateData.set(object, value);
}
for(object) {
return {
init: PrivateProperty.prototype.init.bind(this, boundObject),
hasValue: PrivateProperty.prototype.hasValue.bind(this, boundObject),
get: PrivateProperty.prototype.get.bind(this, boundObject),
set: PrivateProperty.prototype.set.bind(this, boundObject)
};
}
};
})();