Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - How to override object get fallback

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With a proxy.

const mirror = new Proxy({}, {
  get(_, prop) { return prop; }
});
console.log(mirror[1]);
// => 1
console.log(mirror['123']);
// => '123'
console.log(mirror.randomPropertyHere);
// => 'randomPropertyHere'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...