2011-12-26 73 views
4

我希望能够做到这一点有没有办法在调用对象的未定义函数时调用自定义函数?

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

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

我觉得这个功能的确存在,但我无法找到它。

+3

请查看此文章:http://stackoverflow.com/questions/8283362/capture-method-missing-in-javascript-and-do-some-logic – 2011-12-26 05:35:18

回答

2

在当前状态下,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'不存在

相关问题