javascript - 函数代理 .toString() 错误

标签 javascript ecmascript-6 tostring es6-proxy

我正在尝试在函数代理上调用 .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/

相关文章:

java - 从 org.apache.commons.lang3.builder.ToStringStyle 访问 NO_CLASS_NAME_STYLE 字段时出错

java - 使用 toString 方法但组合框仍然不显示值

javascript - Cypress 通过包含的文本过滤选定的元素

javascript - 如何将数据推送到 JavaScript 对象文字

javascript - 如何将表单元素传递给 javascript 验证函数?

javascript - 将带数组的对象转换为带对象的数组的最佳方法,反之亦然

javascript - 多次加载animate cc的html5 canvas publish

javascript - 如何在 ES6 中解构为动态命名的变量?

javascript - 过滤对象的嵌套数组

c# - 如何在 C# 中将 nchar 转换为字符串?