Is ES6 safe to use a static class variable as a key for a map?

In babel-preset-stage-0we can declare a static class variable as follows:

class Constants {
  static COUNTRY = Object.freeze({
      NAME: 'Germany',
      DESCRIPTION: 'placeholder',
  })
}

Can I use Constants.COUNTRYas a key for ES6 Mapor Set?

eg.

const map = new Map();
map.add(Constants.COUNTRY, something);

Is it guaranteed that map.get(Constants.COUNTRY)it will always return something?

Is performance as useful as using strings as a key? Is it safe to use Constants.COUNTRYlike eventKey(attribute of bootstrap component) for NavItemtoo?

Is it also more appropriate to declare it as a variable instead of a class? i.e.

const Constants = Object.freeze({
  COUNTRY: Object.freeze({
      NAME: 'Germany',
      DESCRIPTION: 'placeholder',
  })
}) 
+4
2

map.get(Constants.COUNTRY) - ?

map.get(Constants.COUNTRY) , .

  • , Constants.COUNTRY , .COUNTRY , , Constants - , .COUNTRY .

  • , map.

, map.get(Constants.COUNTRY) . , , , .

, Constants.COUNTRY Constants , , , . , Constants , , const, .

, , map.delete(Constants.COUNTRY), , map , .

- , ( - , ), WeakMap map.

, ?

Javascript, . , - .

jsPerf, . , /, , 10 000 10 000 , 1000 , .

Chrome is ~20% slower to access the object keys.
Firefox is ~20% slower to access the string keys.
Edge is ~27% slower to access the string keys.

?

, const , Constants .

+2

WeakMap to COUNTRY , something - . , const, . Object.freeze(), wm.get(COUNTRY) something

  const wm = new WeakMap;

  const COUNTRY = Object.freeze({
    NAME: 'Germany',
    DESCRIPTION: 'placeholder',
  });

  wm.set(COUNTRY, "something");

  // error when "use strict"
  delete wm;
  delete COUNTRY;

  COUNTRY.NAME = 123;

  console.log(
    wm.get(COUNTRY)
  );
  
  console.log(
    COUNTRY
  );
  
  console.log(
    wm
  );
Hide result

, , const . , const? JSON

"use strict";

// `Constants` cannot be changed or deleted
const Constants = `{
  "NAME": "Germany",
  "DESCRIPTION": "placeholder"
}`;

console.log(
  JSON.parse(Constants)
);

// delete Constants;
/*
Error: {
  "message": "Uncaught SyntaxError: Delete of an unqualified identifier in strict mode."
}
*/
Hide result
0

Source: https://habr.com/ru/post/1681927/


All Articles