mardi 31 janvier 2023

Programmatically check in runtime whether variable is const in JavaScript?

Is it possible to know programmatically in runtime whether variable is const in JS?

For example:

const a = {};
const b = 5;

var c = {};
var d = 6;

var e = a;
var f = b;
var g = c;
var h = d;

isConst(a); // true
isConst(b); // true
isConst(c); // false
isConst(d); // false
isConst(e); // false
isConst(f); // false
isConst(g); // false
isConst(h); // false

I don't even know how to approach this issue, assuming I don't want to use external tools (from outside the JS runtime environment), or something like eval().

Maybe it's possible somehow with JavaScript's Proxy() or Reflect()?

If there's no solution that determine if const or not without making changes in the checked code/module/function/block itself, I can maybe accept solutions that require some decorative/wrapping modifications to the code/function.

Maybe something that parse the Function() prototype field that contains the stringified text of the function body?

Maybe we can leverage exceptions here? For example, to catch the exception that raised when you try to manipulate a constant variable, and use it to understand the situation?





Aucun commentaire:

Enregistrer un commentaire