Reputation: 33
I was looking for a way to convert something in dot notation into a string using Javascript. Basically here's what I am looking for:
function dotToString(dotNotation){
return something;
}
dotToString(this.is.just.a.test);
// Would return "this.is.just.a.test"
Upvotes: 0
Views: 376
Reputation:
Yes, you can do this with proxies.
function makeDotProxy(name) {
return new Proxy({}, {
get(target, prop) {
if (prop === 'valueOf' || prop === 'toString') return () => name;
if (typeof prop === 'symbol') return Reflect.get(target, prop);
return makeDotProxy(name + '.' + prop);
}
});
}
const This = makeDotProxy('this');
console.log(This.is.a.just.a.test.toString());
But then, why would you want to?
Upvotes: 1
Reputation: 22911
Short answer: No
Long answer: When javascript passes an argument to a function, it passes in the value from the variable you are attempting to pass in. At no point does the dotToString
function see this.is.just.a.test
(It would see "blah", if this.is.just.a.test = "blah"
). This is not possible.
Upvotes: 3