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

Le *_*con 4 javascript metaprogramming object interceptor

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

const object = {};
// an error should be thrown
object.property.someMethod();
// an error should be thrown
object.foo;
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助,将不胜感激.

Pat*_*rts 7

是的,使用Proxy一个handler.get()陷阱:

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

object.foo
Run Code Online (Sandbox Code Playgroud)

如果要使用此行为修改现有对象,可以使用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)
Run Code Online (Sandbox Code Playgroud)