Force JavaScript exception/error when reading an undefined object property?

后端 未结 7 1198
后悔当初
后悔当初 2020-11-30 04:29

I\'m an experienced C++/Java programmer working in Javascript for the first time. I\'m using Chrome as the browser.

I\'ve created several Javascript classes with fie

7条回答
  •  猫巷女王i
    2020-11-30 05:22

    This can be achieved using ES6 proxies:

    function disallowUndefinedProperties(obj) {
        const handler = {
            get(target, property) {
                if (property in target) {
                    return target[property];
                }
    
                throw new Error(`Property '${property}' is not defined`);
            }
        };
    
        return new Proxy(obj, handler);
    }
    
    // example
    const obj = { key: 'value' };
    const noUndefObj = disallowUndefinedProperties(obj);
    
    console.log(noUndefObj.key);
    console.log(noUndefObj.undefinedProperty); // throws exception

提交回复
热议问题