使用以下代码:
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:无法将Symbol值转换为字符串
这就发生在这一行:
new Error(`The assertion library used does not have '${prop}' property or method.`));
之前我使用过Proxies,我从未见过将Symbols传递给Proxy的get方法。有谁知道如何规避这个问题?
为什么符号被传递给代理获取功能以及如何正确处理?
答案 0 :(得分:2)
为什么符号被传递给代理获取功能?
我们不知道,您没有显示任何实际使用代理的代码。但是许多符号可以通过内置方法访问,例如当您迭代代理时,它使用Symbol.iterator
方法。
我该如何妥善处理?
您无法将符号与字符串连接起来,您需要明确这样做。您可以使用prop.toString()
或只根据typeof prop
进行切换。