Is there a way to call a user-defined function when calling an undefined function?

I want to be able to do it

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

I think this function exists, but I cannot find it.

+4
source share
1 answer

In its current state, JavaScript does not support the exact functions you need. The post in the commentary gives detailed information about what can and cannot be done. However, if you are ready to refuse the use of "." invoke method, heres a sample code 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

The 'sho' method does not exist

+2
source

Source: https://habr.com/ru/post/1387984/


All Articles