Suppose I have a function Foo
, and I want objects constructed from it to have a bar
property:
function Foo() {}
Foo.prototype.bar = 'baz'
console.log('new Foo().bar: ' + new Foo().bar)
new Foo().bar: baz
Now suppose I bind Foo
in some way. Bound functions can still be used in constructor calls, and the bound this
is ignored:
const Bound = Foo.bind(42)
console.log('new Bound().bar: ' + new Bound().bar)
new Bound().bar: baz
Proxies are supposed to be general and transparent. However...
const PFoo = new Proxy(Foo, { })
console.log('new PFoo().bar: ' + new PFoo().bar)
const PBound = new Proxy(Bound, { })
console.log('new PBound().bar: ' + new PBound().bar)
new PFoo().bar: baz
new PBound().bar: undefined
I would expect the second proxy to behave exactly as Bound
, since I am using an empty handler. In other words, I would expect the last output to be baz
.
Why is it not the case?
(complete snippet follows)
function Foo() {}
Foo.prototype.bar = 'baz'
console.log('new Foo().bar: ' + new Foo().bar)
const Bound = Foo.bind(42)
console.log('new Bound().bar: ' + new Bound().bar)
const PFoo = new Proxy(Foo, { })
console.log('new PFoo().bar: ' + new PFoo().bar)
const PBound = new Proxy(Bound, { })
console.log('new PBound().bar: ' + new PBound().bar)
.prototype
object but they appear to search for it from their origin whennew
is used, while proxied functions only provide it if the original has it directly. So there must be some difference in how the.prototype
is requested. The spec will have the answer if anyone cares to check. – Solnitprototype
from bound function, but never heard/thought of the proxied function only providing it if the proxied function has it directly. Will check, thanks for the input. – Laidconsole.log("new.target:", new.target.name);
in theFoo
constructor yields an interesting result. – Solnitnew.target
was correct, thanks. I think I got it, I will write an answer with some details from the spec. Not sure this is actually a feature though... – Laid