利用具有指定屬性的符號
P粉517090748
P粉517090748 2023-09-18 12:45:11
0
1
542

如下所示的程式碼中,我定義了一些常數。我想使用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'。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板