我只是想检查的对象是Map或Set,而不是一个Array.
检查我正在使用lodash的数组_.isArray.
function myFunc(arg) {
if (_.isArray(arg)) {
// doSomethingWithArray(arg)
}
if (isMap(arg)) {
// doSomethingWithMap(arg)
}
if (isSet(arg)) {
// doSomethingWithSet(arg)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我要实现isMap/ isSet,它需要看起来像什么?我希望它能够捕获Map/的子类,Set如果可能的话.
我正在使用Chrome 60。我刚刚尝试在 上应用get 代理window.location。
它适用于前两个参考,但是,随后失败并出现Illegal invocation错误:
location = new Proxy(location, {\n get: (target, name) => {\n console.log(name, target, "PROX");\n return target[name];\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n错误消息是:
\n\n\nVM3495:3 符号(Symbol.toPrimitive) 位置 {\xe2\x80\xa6} "PROX"
\nVM3495:3 toString 位置 {\xe2\x80\xa6} PROX
\n未捕获的类型错误:非法调用:1:10
\n
get代理window.location?我通过Google Chrome版本57.0.2987.133运行以下脚本:
var loggingProxyHandler = {
"get" : function(targetObj, propName, receiverProxy) {
let ret = Reflect.get(targetObj, propName, receiverProxy);
console.log("get("+propName.toString()+"="+ret+")");
return ret;
},
"set" : function(targetObj, propName, propValue, receiverProxy) {
console.log("set("+propName.toString()+"="+propValue+")");
return Reflect.set(targetObj, propName, propValue, receiverProxy);
}
};
function onRunTest()
{
let m1 = new Map();
let p1 = new Proxy(m1, loggingProxyHandler);
p1.set("a", "aval"); // Exception thrown from here
}
onRunTest();Run Code Online (Sandbox Code Playgroud)
NOTE: Requires a browser supporting ES2015's ProxyRun Code Online (Sandbox Code Playgroud)
运行时,我看到调用处理程序的get陷阱来返回Map的set函数,然后我收到以下错误:
"Uncaught TypeError: Method Map.prototype.set called on incompatible receiver [object Object]"
at Proxy.set …Run Code Online (Sandbox Code Playgroud)