【问题标题】:Function Proxy .toString() Errors函数代理 .toString() 错误
【发布时间】:2016-07-08 06:03:33
【问题描述】:

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

简单创建一个函数代理,调用toString会导致“TypeError: Function.prototype.toString is not generic”,设置toString返回源原来会导致“RangeError: Maximum call stack size exceeded”,但是创建一个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()

【问题讨论】:

  • 不相关:return 是关键字,本身不是函数,所以它是 return x 而不是 return(x)。括号在这里没有做任何事情。

标签: javascript ecmascript-6 tostring es6-proxy


【解决方案1】:

我遇到了同样的问题。我终于发现这是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());

【讨论】:

    【解决方案2】:

    TypeError: Function.prototype.toString 不是通用的

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多