【问题标题】:Is it possible to construct an object so that it throws an error when its keys are requested?是否可以构造一个对象,以便在请求其键时引发错误?
【发布时间】:2019-02-26 05:55:55
【问题描述】:

假设我有以下代码:

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

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

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

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript object metaprogramming interceptor


    【解决方案1】:

    是的,使用 Proxyhandler.get() 陷阱:

    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)

    【讨论】:

    • 如果在已经存在的对象上使用它,例如{name: "Fred", age: 42},那么get 处理程序只需检查获取的属性是否在目标get(target, property) { if (!(property in target)) { throw new Error(); } else return target[property]; }
    • 是否也值得将上下文转发给 Reflect.get 方法?
    • @Michael 好点子,以防 getter 访问对象上不存在的属性。
    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2015-04-01
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多