简体   繁体   中英

autoload another method if method is undefined in javascript

Can i fallback to another method if method of a given object is not found?

say i've got (just to get the idea)

var phoneCall new function() {

  function toMom() {

  }

  function catchAll() {

  }

 }

q = new phoneCall;
q.toMom();

q.toDad() //should fire phoneCall.catchAll();

No - not in a cross-browser way. Firefox and a couple other engines have an approach to do this, but it won't work in Chrome, IE, etc. Proxies will eventually allow some functionality like this, but that's still in the early phase of engine adoption.


Edit: here's some code that might get you started with something that will work though:

 var phoneCall = { to: function(whom) { (phoneCall.people[whom] || phoneCall.catchAll)(); }, people: { mom: function() { // call mom functionality } }, catchAll: function() { // generic call functionality } }; phoneCall.to('mom'); phoneCall.to('dad'); // invokes catchAll 

You could do something like that:

q.toDad() || q.catchAll();

EDIT:

User jmar77 is right about this code being invalid, since it is returning a function's result rather than the function itself... My bad. Here's the updated code:

function phoneCall() {
   this.toMom = function() {
        console.log('Mom was called.');
    }
   this.catchAll = function() {
        console.log('Catch all was called');
    }
}

q = new phoneCall();
q.toMom();
q.toDad ? q.toDad() : q.catchAll();​

http://jsfiddle.net/remibreton/yzDh7/

Use a getter pattern:

http://jsfiddle.net/XjgPW/1/

var myObject = (function() {
    var methods = {
        method1: function () {
            console.log('method1 called');
        },
        method2: function () {
            console.log('method2 called');
        },  
        defaultMethod: function () {
            console.log('defaultMethod called');
        }
    };

    var get = function (name) {
        if (methods.hasOwnProperty(name)) {
            return methods[name];
        } else {
            return methods.defaultMethod;
        }
    };

    return {
        get: get
    };
}());

The following code demonstrates calling a fallback method if the first method doesn't exist:

q = {};
q.toDad = function() {
    console.log("to dad");
}
(q.toMom || q.toDad)();  // Will output "to dad" to the console

q.toMom = function() {
    console.log("to mom");
}
(q.toMom || q.toDad)();  // Will output "to mom" to the console

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