如下所示的程式碼中,我定義了一些常數。我想使用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'));
polygDigiConstants.js
#JS
polygDigiConstants.CONST_STRING_DIGITIZE將直接給你字串'Digitize'。