利用具有指定属性的符号
P粉517090748
P粉517090748 2023-09-18 12:45:11
0
1
545

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

全部回复(1)
P粉200138510

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'。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板