Daniel Rustrum
Daniel Rustrum

Reputation: 1

Proxy only return target through get method when trying to return a different value

I am trying to just give the user the string "Hello" everytime the proxy is called through the get method. Instead, I am getting an empty object, which is my target.

I've tried to use classes like String, Reflect with no positive results

let proxy = new Proxy({},{
    get: function ()
    {
         return "Hello"
    }
})


console.log(proxy)

Expected: "Hello"
Result: {}

Upvotes: 0

Views: 613

Answers (2)

Brook
Brook

Reputation: 305

Possible if you covert it to string

let proxy = new Proxy({},{
    get: function ()
    {
         return () => "Hello" // Proxy Symbol.toPrimitive
    }
})
console.log(String(proxy), proxy == 'Hello')

Upvotes: 1

Bergi
Bergi

Reputation: 665276

every time the proxy is called through the get method.

That's not what the get trap is made for. The method will handle property accesses, not accesses of the proxy itself. Your (proxy) object doesn't have any properties, they are not accessed, so all you see is the empty object.

See the get trap in action here:

const proxy = new Proxy({},{
    get: function () {
         return "Hello"
    }
})
console.log(proxy.someProperty, proxy.really, proxy.anything)
console.log(proxy)

I am trying to just give the user the string "Hello"

That's not possible. A proxy is always an object. It cannot masquerade as a primitive string.

Upvotes: 2

Related Questions