【问题标题】:Is there a way to have a custom function be called when an object's undefined function is called?有没有办法在调用对象的未定义函数时调用自定义函数?
【发布时间】:2011-12-26 05:31:16
【问题描述】:

我希望能够做到这一点

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

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

我认为这个功能确实存在,但我找不到。

【问题讨论】:

标签: javascript object


【解决方案1】:

在当前状态下,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");

输出:

你好

方法'sho'不存在

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2023-03-21
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多