搜索

首页  >  问答  >  正文

利用具有指定属性的符号

如下所示的代码中,我定义了一些常量。我想使用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)

上述代码的输出为:

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'));
P粉517090748P粉517090748437 天前540

全部回复(1)我来回复

  • 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将直接给你字符串'Digitize'。

    回复
    0
  • 取消回复