Is there a thing such as method_missing in Javascript?

Y

yeah

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...
 
Y

yeah

I think you did not get my question. Whenever I call a method on obj
that hasn't been defined in that class, method_missing is executed.
Acts like a fallback...
 
R

RobG

yeah said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top