fent
fent

Reputation: 18205

Is there a way to have a custom function be called when an object's undefined function is called?

I want to be able to do this

var o = {
};
o.functionNotFound(function(name, args) {
  console.log(name + ' does not exist');
});

o.idontexist(); // idontexist does not exist

I think this feature does exist but I can't find it.

Upvotes: 4

Views: 84

Answers (1)

Abbas
Abbas

Reputation: 6886

In its current state, JavaScript does not support the exact functionality that you require. The post in the comment gives details on what can and cannot be done. However, if you are willing to forego the use of the “.” method invocation, here’s a code sample that is close to what you want:

var o = 
{
    show: function(m)
    {
        alert(m);
    },

    invoke: function(methname, args)
    {
        try
        {
            this[methname](args);
        }
        catch(e)
        {
            alert("Method '" + methname + "' does not exist");
        }   
    }
}

o.invoke("show", "hello");
o.invoke("sho", "hello");

Output:

hello

Method 'sho' does not exist

Upvotes: 2

Related Questions