Cannot properly Proxy 'os' methods
oNaiPs opened this issue · 2 comments
oNaiPs commented
I cannot get the following example to work:
require('harmonize')(['harmony_proxies']);
require('harmony-reflect');
var os = require('os');
var p = new Proxy(os, {});
console.log(os.type())
console.log(p.type())
This is what I get as output:
Linux
(...)file.js:9
console.log(p.type())
^
TypeError: Illegal invocation
at Object.<anonymous> (/home/onaips/node-lazy-require/oi.js:9:15)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
Looks like the this
context is not being properly set. Is this a bug or I shouldn't be doing it?
tvcutsem commented
By default, a proxy will pass the proxy itself as the this
value to a forwarded method call. Since the os.type
method expects a real os
object as its this
value, the call fails.
To avoid this, try overriding the proxy handler's get
method to return a function that binds this
to the target object that it wraps:
var p = new Proxy(os, {
get: function(target, name, receiver) {
if (typeof target[name] === "function") {
return target[name].bind(target);
}
return Reflect.get(target, name, receiver);
}
})
Does this solve your problem?
oNaiPs commented
Indeed it helps! I ended up changing it to
get: function(receiver, name) {
var target = this.ensureInitialized(target);
if (isNative(target[name])) {
return target[name].bind(target);
}
return Reflect.get(target, name, receiver);
},
Not sure if it would make sense this project though.
Thanks!