Private Properties

Simple Store to implement private properties for a specific Object. Property-names are converted to Symbol-properties and attached to the specified Object.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://greasyfork.org/scripts/390833-private-properties/code/Private%20Properties.js?version=739191

Author
Gerrit
Ratings
0 0 0
Version
0.1
Created
Updated
License
N/A
Applies to
All sites

Author's Description

/**
 * Usage Example
 */
const MyClass = (() => {

    const _ = new PrivateStore();

    class MyClass {
        constructor(valueOfProperty1) {
            _.set(this, "property1", valueOfProperty1);
        }

        set property1(value) {
            _.set(this, "property1", value);
        }

        get property1() {
            return _.get(this, "property1");
        }

        get property2() {
            return _.getOrCompute(this, "property2", () => {
                // return ...
            });
        }
    }
    return MyClass;
})();

/**
 * Equivalent solution without this library
 */
const MyClass2 = (() => {

    const _property1 = Symbol("property1");
    const _property2 = Symbol("property2");

    class MyClass2 {
        constructor(valueOfProperty1) {
            this[_property1] = valueOfProperty1;
        }

        set property1(value) {
            this[_property1] = value;
        }

        get property1() {
            return this[_property1];
        }

        get property2() {
            return this[_property2] || (this[_property2] = () => {
                // return ...
            });
        }
    }
    return MyClass2;
})();