繁体   English   中英

是否可以构造一个对象,以便在请求其键时抛出错误?

[英]Is it possible to construct an object so that it throws an error when its keys are requested?

想象一下,我有以下代码:

const object = {};
// an error should be thrown
object.property.someMethod();
// an error should be thrown
object.foo;

调用someMethod()或调用任何其他不存在的属性时是否可能抛出错误?

我想我需要用它的原型做一些事情,抛出一个错误。 但是,我不确定我应该做什么。

任何帮助,将不胜感激。

是的,使用带有handler.get()陷阱的Proxy

 const object = new Proxy({}, { get (target, key) { throw new Error(`attempted access of nonexistent key \\`${key}\\``); } }) object.foo 

如果要使用此行为修改现有对象,可以使用Reflect.has()检查属性是否存在,并确定是使用Reflect.get()转发访问还是throw

 const object = new Proxy({ name: 'Fred', age: 42, get foo () { return this.bar } }, { get (target, key, receiver) { if (Reflect.has(target, key)) { return Reflect.get(target, key, receiver) } else { throw new Error(`attempted access of nonexistent key \\`${key}\\``) } } }) console.log(object.name) console.log(object.age) console.log(object.foo) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM