search

Home  >  Q&A  >  body text

Utilize symbols with specified properties

In the code shown below, I have defined some constants. I want to use Symbol to ensure each constant is unique. But when I use the following line of code:

if (isBtnDigitizePolygonClicked.value == true) {
    return polygDigiConstants.CONST_STRING_DIGITIZE;
}

The value returned by the above code is Symbol('Digitize'), but I expected it to be Digitize as described in this tutorial: https://www. scaler.com/topics/enum-in-javascript/

Tutorial content:

const Direction = Object.freeze({
  North: Symbol('north'),
  East: Symbol('east'),
  West: Symbol('west'),
  South: Symbol('south'),
})

const Pole = Object.freeze({
  North: Symbol('north'),
  South: Symbol('south'),
})

console.log(Direction.North === Pole.North)

上述代码的输出为:

false

Please tell me how to use Symbol correctly to define properties.

polygDigiConstants.js

function define(name, value) {
Object.defineProperty(polygDigiConstants, name, {
    value: value,
    enumerable: true,
    writable: false,
});
}

export let polygDigiConstants = {};

define('CONST_STRING_DIGITIZE', Symbol('Digitize'));
define('CONST_STRING_STOP_DIGITIZE', Symbol('Stop'));
define('CONST_STRING_CLEAR_DIGITIZED', Symbol('Clear'));
P粉517090748P粉517090748527 days ago591

reply all(1)I'll reply

  • P粉200138510

    P粉2001385102023-09-19 11:37:35

    polygDigiConstants.js

    function define(name, value) {
        Object.defineProperty(polygDigiConstants, name, {
            value: value,
            enumerable: true,
            writable: false,
        });
    }
    
    export let polygDigiConstants = {};
    
    define('CONST_STRING_DIGITIZE', Symbol('Digitize'));
    define('CONST_STRING_STOP_DIGITIZE', Symbol('Stop'));
    define('CONST_STRING_CLEAR_DIGITIZED', Symbol('Clear'));

    JS

    import { polygDigiConstants } from './polygDigiConstants.js';
        
        if (isBtnDigitizePolygonClicked.value == true) {
            return polygDigiConstants.CONST_STRING_DIGITIZE.description; // 这将给你 'Digitize'
        }
    
    function define(name, value) {
        Object.defineProperty(polygDigiConstants, name, {
            value: value,
            enumerable: true,
            writable: false,
        });
    }
    
    export let polygDigiConstants = {};
    
    define('CONST_STRING_DIGITIZE', 'Digitize');
    define('CONST_STRING_STOP_DIGITIZE', 'Stop');
    define('CONST_STRING_CLEAR_DIGITIZED', 'Clear');

    polygDigiConstants.CONST_STRING_DIGITIZE will give you the string 'Digitize' directly.

    reply
    0
  • Cancelreply