NodeJS 如何使用具有已定义属性的符号

unftdfkk  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(105)

如下面的代码所示,我定义了一些常量。我想使用Symbol,这样每个常量都是唯一的。但是当我使用,例如,下面的代码行:

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

字符串
上面的代码返回的值是Symbol('Digitize'),我希望它是Digitize,如本教程所述:https://www.scaler.com/topics/enum-in-javascript/

教程内容

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)

The output of the above code is :

false


请让我知道如何正确使用Symbol与定义的属性

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'));

ss2ws0br

ss2ws0br1#

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; // This will give you '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将直接给予字符串'Digitize'。

相关问题