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

后端 未结 7 1185
后悔当初
后悔当初 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 05:22

    This looks to me like a classic case of trying to shoehorn one language into the paradigms of another - better IMHO to change your coding style to follow how Javascript does things than try to make it conform to C++ concepts and expectations.

    That said, if you want to throw an error as you suggest, you'll need to define some sort of custom getProperty function, either on the object you're trying to access or in the global scope. An implementation might look like this:

    function getProperty(o, prop) {
        if (o.hasOwnProperty(prop)) return o[prop];
        else throw new ReferenceError('The property ' + prop + 
            ' is not defined on this object');
    }
    
    var o = {
        foo: 1,
        bar: false,
        baz: undefined
    };
    
    getProperty(o, 'foo'); // 1
    getProperty(o, 'bar'); // false
    getProperty(o, 'baz'); // undefined
    getProperty(o, 'foobar'); 
    // ReferenceError: The property baz is not defined on this object
    

    But this is ugly, and now you've got this custom language construct in all of your code, making it less portable (if, for example, you wanted to copy any part of your code into another script, you'd have to copy your new function too) and less legible to other programmers. So I'd really recommend working within the Javascript paradigm and checking for undefined before accessing the properties you need (or setting up your code so that false-y values are expected and don't break things).

    As to your second question, why Javascript throws an error for undefined variables but not for undefined object properties, I can't give any better answer than "Because that's what's in the language specification." Objects return undefined for undefined property names, but undefined variable references throw an error.

提交回复
热议问题