是否有一种方法可以在调用对象的未定义函数时调用自定义函数?

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

本文关键字:调用 对象 未定义 函数 自定义函数 方法 一种 是否      更新时间:2023-09-26

我希望能够做到这一点

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

我想这个功能是存在的,但是我找不到。

在当前状态下,JavaScript不支持您所需要的确切功能。评论中的帖子详细说明了什么可以做,什么不可以做。然而,如果你愿意放弃使用"。方法调用,这里有一个代码示例,接近您想要的:

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");
输出:

你好

方法' shoo '不存在