yeah wrote:
In Ruby I can define a special method_missing method in my class like
so:
class MyClass
def do_something
"did it"
end
def method_missing
"could not do that, let's do something instead: " + do_something
end
end
Consequently the following statements would have the indicated results:
obj = new MyClass
obj.do_something #--"did it"
obj.do_something_else #--"could not do that, let's do something
instead: did it"
Is such a thing possible in JavaScript? Note: I do not know at design
time which method could possible be called on my objects...
You can check if a method exists using:
if (typeof obj.do_something == 'function'){ /* use do_something */ }
However if you don't know that the method exists, how do you know how
to use it?
Some libraries have a "tryThese" function that use try..catch to try
functions in succession until one works, which is an abomination to
anyone with any interest in a quality design.
I think you are better off to say what you are trying to do at an
architectural level so that you get suggestions on how to best achieve
that using javascript, rather than asking how to implement a solution
from another language.
For example, instead of using try..catch, you can write your functions
to check internally if they have "worked" and return false if they
haven't. Then you can try them in sequence until one returns !false.
Or design a test up-front to work out which one to call, or to change
the function referenced by a particular variable.
There are many ways to skin a cat - your criteria for success and
available tools will determine which is best.
--
Rob