Dynamically access const and let declarations
Change class name on click in jQuery
by pilafmon
HTML
<p>
<code>window[name]</code> equivalent to dynamically access
<code>const</code> and <code>let</code> declarations
</p>
<output></output>
CSS
body {
font-family: system-ui, sans-serif;
background: lightblue;
margin: 20px;
}
output {
display: block;
background-color: khaki;
padding: 10px;
}
JavaScript
var x = 3;
const y = 7;
let z = 21;
const malware = 'alert("Game over.");';
const libraryA = {
getDeclaration(name) {
const validId = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/;
const topLevelGet = (null, eval);
const isNumber = () => topLevelGet('typeof ' + name) === 'number';
return validId.test(name) && isNumber() ? topLevelGet(name) : null;
},
setup() {
const log = (message) => {
const output = globalThis.document.getElementsByTagName('output')[0];
const elem = globalThis.document.createElement('div');
elem.innerText = message;
output.append(elem);
};
log('x = ' + libraryA.getDeclaration('x')); //x = 3
log('y = ' + libraryA.getDeclaration('y')); //x = 7
log('z = ' + libraryA.getDeclaration('z')); //x = 21
log('bogus = ' + libraryA.getDeclaration('bogus')); //bogus = null
log('malware = ' + libraryA.getDeclaration('malware')); //malware = null
log('if = ' + libraryA.getDeclaration('if')); //EXCEPTION: unexpected keyword
},
};
//eval(malware);
libraryA.setup();