Greasy Fork

PrivateFieldAccessor

symbol-like object with initialValue to create private fields

目前为 2019-10-25 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.cloud/scripts/391608/743909/PrivateFieldAccessor.js

// ==UserScript==
// @name         PrivateFieldAccessor
// @namespace    hoehleg.userscripts.private
// @version      0.1
// @description  symbol-like object with initialValue to create private fields
// @author       Gerrit Höhle
// @grant        none
// ==/UserScript==

/* jshint esversion: 6 */
const PrivateFieldAccessor = (() => {
    'use strict';
    return class PrivateFieldAccessor {
        
        constructor(description, initialValue) {
            this.symbol = Symbol(description);
            this.initialValue = initialValue;
        }
        
        init(object) {
            object[this] = this.initialValue;
        }
        
        get(object) {
            if (!Object.prototype.hasOwnProperty.call(object, this)) {
                this.init(object);
            }
            return object[this];
        }
        
        valueOf() {
            return this.symbol;
        }
        
        toString() {
            return this.symbol.description;
        }
    };
})();