函数代理.toString()错误

问题描述:

我想在函数代理上调用.toString()。函数代理.toString()错误

只需创建一个函数代理和调用toString导致“类型错误:Function.prototype.toString是不通用的”,设置了toString返回原来的原因“的RangeError:最大调用堆栈大小超出”的来源,但创建为toString工作获得陷阱。

为什么简单地设置toString函数不起作用,但是做出陷阱呢?

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()

+0

相关:https://开头esdiscuss。 org/topic/calling-tostring-on-function-proxy-throws-typeerror-exception – tybro0103

+0

不相关:'return'是一个关键字,本身不是函数,所以它是'return x'而不是'return(x)'。 parens在这里没有做任何事情。 – Albin

TypeError: Function.prototype.toString is not generic

似乎不应该在Proxy上调用Function.prototype.toString

proxy.toString = function() { 

由于您没有赋值陷阱,因此将此代理转让传递给source对象。如果你检查source.hasOwnProperty('toString')你会得到true。当您添加get陷阱时,您不会更改toString方法,也不会将其添加到source对象中,因此它可以正常工作。

其他可能的解决方案是

function wrap(source) { 
    let proxy = new Proxy(source, {}) 
    proxy.toString = Function.prototype.toString.bind(source) 
    return proxy 
} 

我有同样的问题。我终于发现这是this的问题。一个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());