I'm trying to create an object that returns the property name for any property that was accessed. Is this possible to do cleanly in javascript / nodejs? This is what I would like to accomplish:
const mirror = {/*...*/};
console.log(mirror[1]);
// => 1
console.log(mirror.123);
// => '123'
console.log(mirror.randomPropertyHere);
// => 'randomPropertyHere'
I can overwrite a getter for a specific property, but I don't know how to do it generically. Also how can I differentiate between a number and a string?
My (not working) attempts
const mirror = {
get[1] () {
console.log('number');
return 1;
},
get['1'] () {
console.log('string');
return '1';
}
};
console.log(mirror[1]);
console.log(mirror['1']);
Very much appreciate your time and help!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…