Sean Anderson
Sean Anderson

Reputation: 29301

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?

Upvotes: 3

Views: 777

Answers (1)

Somrlik
Somrlik

Reputation: 740

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/

Upvotes: 5

Related Questions