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

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() 或调用任何其他不存在的 属性 时是否可能抛出错误?

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

如有任何帮助,我们将不胜感激。

是,使用 Proxy with a handler.get() 陷阱:

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

object.foo

如果你想用这种行为修改现有对象,你可以使用Reflect.has() to check for property existence and determine whether to forward the access using 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)