【问题标题】:Symbol vs. String when retrieving property from target object, using ES6 Proxy object使用 ES6 代理对象从目标对象检索属性时的符号与字符串
【发布时间】:2017-09-28 21:55:32
【问题描述】:

使用以下代码:

 const assrt = function () {
    try {
      return chaiAssert.apply(null, arguments);
    }
    catch (e) {
      return handleError(e);
    }
  };

 v.assert = new Proxy(assrt, {
    get: function (target, prop) {

      if(typeof prop === 'symbol'){
        // I don't know what to do with symbols, so return
         return Reflect.get(...arguments);
      }

      // but here! we still get properties that don't exist
      if(!chaiAssert[prop]){
        return handleError(
          new Error(`The assertion library used does not have '${prop}' property or method.`)
        );
      }

      return function () {
        try {
          return chaiAssert[prop].apply(null, arguments);
        }
        catch (e) {
          return handleError(e);
        }
      }
    }
  });

我使用此代码得到的错误是:

TypeError:无法将符号值转换为字符串

这发生在行:

new Error(`The assertion library used does not have '${prop}' property or method.`));

我以前使用过代理,但从未见过将符号传递给代理的 get 方法。有谁知道如何规避这个问题?

为什么要将符号传递给代理获取函数,我该如何正确处理?

【问题讨论】:

  • 被发送到 get 函数的 prop 是 Symbol(util.inspect.custom),并且认为还有其他的被发送。
  • 我认为,您必须调试代码。 if(typeof prop === 'symbol'){ 似乎不需要过滤掉符号。

标签: javascript node.js es6-proxy


【解决方案1】:

为什么要将符号传递给代理获取函数?

我们不知道,您没有显示任何实际使用代理的代码。但是许多符号是通过内置方法访问的,例如当您迭代代理时,它使用Symbol.iterator 方法。

我该如何正确处理呢?

您不能将符号与字符串连接,您需要明确说明这样做。您可以使用prop.toString() 或仅基于typeof prop 切换。

【讨论】:

  • 你能通过打开typeof prop来演示你的意思吗
  • typeof prop == "symbol" ? "Symbol ["+prop.toString()+"]" : prop 或任何你想对符号做的事情。也许只是在您的代理处理程序中完全忽略它们,并为它们返回默认的Reflect.get
  • 是的,我不知道如何处理这些符号,但我需要在符号通过时将他们正在寻找的内容传回......你能按照你的建议展示如何使用 Reflect 吗?
  • 看起来像这样 => return Reflect.get(...arguments)
  • 我很困惑为什么非符号属性会被传递给处理程序的 get 方法,而目标属性将不存在于目标上。我会更新 OP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 2011-12-24
  • 2019-11-24
相关资源
最近更新 更多