0

Given the function object:

var foo = function foo() {
    return "My methods are bar and baz";
};
foo.bar = function () {return "ok";};
foo.prototype.baz = function () {return "ok";};

If foo.bar() or foo.baz() are called, they respond with ok. However, if I try foo.wrong(), I get an error.

Is there a way for the foo function object to respond with "Invalid method called"? In other words can I see what methods are being called within the foo function object to make sure they are valid (exist)?

For example, since javascript searches the prototype chain for valid functions, is there a way to hook into that search and respond with a function of my own if the search fails (maybe a function I added to the prototype of foo to handle invalid methods)?

I would like to test for this situation within the foo function itself and not externaly every time I attempt to call a method of the foo function object.

Also, please stay within strict mode guidelines.

ciso
  • 2,606
  • 4
  • 28
  • 54
  • in short, you can't. – jcubic Apr 12 '15 at 14:56
  • 1
    You could do it by defining a method that acts as a proxy, and calls the functions if they exist. But I do not see the point of this. You could check if a function is defined before calling it outside the function, but the best is just to have a defined set of functions so you don't have to check if the function exists. – orhanhenrik Apr 12 '15 at 14:57
  • @ChrisGciso Yes. I don't see any other way to do it like you described. But it is still not a good thing to do, I don't understand why you need this functionality? – orhanhenrik Apr 12 '15 at 15:00
  • Then simply do `if(foo.test){/*call foo.test*/}else{/*Can't do it yet :(*/}` – orhanhenrik Apr 12 '15 at 15:08

1 Answers1

3

Since you don't want to check if a function exists every time you call it you can add a call function which checks the function name (as @Izzey suggested):

foo.call = function(name) {
    if('function' === typeof this[name]) {
        return this[name]();
    }else{
        console.error('function not found');
    }
}

And then call each functions by using the call(name) function:

foo.call('bar');
  • 1
    As an addition to this I would add `return this[name].bind(this)`, and then the function call would look like this `foo.call('bar')()` or `foo.call('bar')(1,2,3,4)`. By returning the function instead of the return value of the function your solution becomes more flexible. Also by using `.bind(this)` you do not lose the reference to `this` inside the function. So you function can still read/write properties to the foo object. – orhanhenrik Apr 13 '15 at 15:40