我正在尝试在函数代理上调用 .toString()。
简单地创建函数代理并调用 toString 会导致“TypeError:Function.prototype.toString 不是通用的”,将 toString 设置为返回原始来源会导致“RangeError:超出最大调用堆栈大小”,但创建一个 get toString 的陷阱有效。
为什么简单地设置 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
的问题。向您的处理程序添加一个 get
陷阱,如果它是一个 function
,则将代理对象绑定(bind)为代理属性上的 this
,它似乎工作正常:
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());
关于javascript - 函数代理 .toString() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259885/