函数代理 .toString() 错误 [英] Function Proxy .toString() Errors
问题描述
我正在尝试在函数代理上调用 .toString().
I am trying to call .toString() on a function proxy.
简单地创建函数代理并调用toString导致TypeError: Function.prototype.toString is not generic",设置toString返回源导致RangeError: Maximum call stack size exceeded",但是创建了一个gettoString 的陷阱有效.
Simply creating a function proxy and calling toString causes "TypeError: Function.prototype.toString is not generic", setting the toString to return the source of the original causes "RangeError: Maximum call stack size exceeded", but creating a get trap for toString works.
为什么简单地设置 toString 函数不起作用,但设置一个 get 陷阱却起作用?
Why does simply setting the toString function not work, but making a get trap does?
function wrap(source) {
return(new Proxy(source, {}))
}
wrap(function() { }).toString()
function wrap(source) {
let proxy = new Proxy(source, {})
proxy.toString = function() {
return(source.toString())
}
return(proxy)
}
wrap(function() { }).toString()
function wrap(source) {
return(new Proxy(source, {
get(target, key) {
if(key == "toString") {
return(function() {
return(source.toString())
})
} else {
return(Reflect.get(source, key))
} } })) }
wrap(function() { }).toString()
推荐答案
我遇到了同样的问题.我终于发现这是this
的问题.将 get
陷阱添加到您的处理程序,如果它是 function
,则在代理属性上将代理对象绑定为 this
,并且它似乎可以正常工作:
I was having the same issue. I finally figured out that it's an issue with this
. Add a get
trap to your handler, bind the proxied object as this
on the proxied property if it's a function
, and it seems to work okay:
function wrap(source) {
return new Proxy(source, {
get: function (target, name) {
const property = target[name];
return (typeof property === 'function')
? property.bind(target)
: property;
}
});
}
console.log(wrap(function () {}).toString());
这篇关于函数代理 .toString() 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!