简体   繁体   中英

Fire an error when Object property does not exists

Alias title: Strict mode for object properties

I'm working on a error manager and I want this to be very strict. Suppose you are calling to a property that does not exist, this usually is interpreted as undefined, instead, it should throw an error, ex:

var obj = {};

obj.PI; //throw Error instead of undefined.

Result expected:

Uncaught ReferenceError: obj.PI is not defined

I want to appear this error when we called any property that does not exist, should not necessarily be PI

First off, if you know the specific properties you want to catch access to, then you can provide a getter for those properties and throw an error from the getter.

If you don't know the specific properties and want a catch-all for all undefined property access, then you will need ES6 proxy support which is not widely available yet (appears to be in some versions of Firefox and in Microsoft Edge, but not in Chrome). So, unless this is a Firefox or Edge-specific project, there is no support for what you're asking that is cross browser as this is not an ES5-level feature of Javascript.

FYI, with proxies, it would be the handler.get() method that you would be interested in.

You can see the current level of ES6 proxy support here: https://kangax.github.io/compat-table/es6/

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