尝试访问不存在的属性时引发错误

时间:2016-03-27 04:34:06

标签: javascript

我有一个像这样的对象:

const foo = {
  bar: 'bar'
};

我想修改它,如果有人试图访问不存在的属性,则会抛出错误而不是返回undefined。

例如,

const baz = foo.baz;
// Error: Property 'baz' does not exist on object 'foo'

这可能吗?

1 个答案:

答案 0 :(得分:2)

使用ECMAScript 6,您可以使用代理。

var original = {"foo": "bar"};
var proxy = new Proxy(original, {
    get: function(target, name, receiver) {
        console.log("Name of requested property: " + name);
        var rv = target[name];
        if (rv === undefined) {
          console.log("There is no such thing as " + name + ".")
          rv = "Whatever you like"
        }
        return rv;
    }
});

console.log("original.foo = " + proxy.foo);     // "bar"
console.log("proxy.foo = " + proxy.whatever);   // "Whatever you like"

https://jsfiddle.net/u5b3wx9w/