Error function Proxy.toString ()

I am trying to call .toString () for a proxy function.

Simply creating a proxy function and calling toString raises “TypeError: Function.prototype.toString is not common”, setting toString to return the source of the original reasons “RangeError: Maximum call stack size”, but creating a get trap for toString to work.

Why just setting the toString function does not work, but set a trap for receiving?

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() 
+7
javascript tostring ecmascript-6 es6-proxy
source share
2 answers

TypeError: Function.prototype.toString is not shared

It seems that Function.prototype.toString not supposed to be called on Proxy .

 proxy.toString = function() { 

This proxy assignment is passed to the source object because you do not have a trap for the assignment. If you check source.hasOwnProperty('toString') , you will get true . When you add a get hook, you do not change the toString method or add it to the source object, so it works.

Another possible solution is

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

I had the same problem. I finally realized that this is a problem with this . Add a get hook to your handler, bind a proxy object like this to the proxy server if it is function , and it seems to work fine:

 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()); 
0
source share

All Articles