简体   繁体   中英

Throw error when attempting to access non-existent property

I have an object like:

const foo = {
  bar: 'bar'
};

I would like to modify it such that if someone tried to access a non-existent property an error would be thrown rather than returning undefined.

For example,

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

Is this possible?

With ECMAScript 6 you can use proxies.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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