Is there a way to catch an attempt to access a non existant property or method?

后端 未结 4 1522
星月不相逢
星月不相逢 2020-12-06 00:56

For instance this code:

function stuff() {
  this.onlyMethod = function () {
    return something;
  }
}

// some error is thrown
stuff().nonExistant();
         


        
4条回答
  •  死守一世寂寞
    2020-12-06 01:14

    There is a way to define a generic handler for calls on non-existant methods, but it is non-standard. Checkout the noSuchMethod for Firefox. Will let you route calls to undefined methods dynamically. Seems like v8 is also getting support for it.

    To use it, define this method on any object:

    var a = {};
    
    a.__noSuchMethod__ = function(name, args) {
        console.log("method %s does not exist", name);
    };
    
    a.doSomething(); // logs "method doSomething does not exist"
    

    However, if you want a cross-browser method, then simple try-catch blocks if the way to go:

    try {
        a.doSomething();
    }
    catch(e) {
        // do something
    }
    

    If you don't want to write try-catch throughout the code, then you could add a wrapper to the main object through which all function calls are routed.

    function main() {
        this.call = function(name, args) {
            if(this[name] && typeof this[name] == 'function') {
                this[name].call(args);
            }
            else {
                // handle non-existant method
            }
        },
        this.a = function() {
            alert("a");
        }
    }
    
    var object = new main();
    object.call('a') // alerts "a"
    object.call('garbage') // goes into error-handling code
    

提交回复
热议问题