函数代理 .toString() 错误

2024-01-03

我试图在函数代理上调用 .toString() 。

简单地创建一个函数代理并调用 toString 会导致“TypeError: Function.prototype.toString is not generic”,将 toString 设置为返回原始原因“RangeError: Maximum call stack size returned”的来源,但为 toString 创建一个 get 陷阱作品。

为什么简单地设置 toString 函数不起作用,但设置 get 陷阱却起作用?

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. Add a get陷阱到您的处理程序,将代理对象绑定为this在代理属性上,如果它是function,而且似乎工作正常:

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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

函数代理 .toString() 错误 的相关文章

随机推荐