0

I have 2 js functions:

function onRegionMouseOver()
{
}

function onRegionMouseOut()
{
}

Is it possible to call these js functions dynamically doing something like this?:

var type = 'Out'
//the following line would exec onRegionMouseOut() above:
call(onRegionMouse[type]())

4 Answers 4

4

You can use this:

var onRegionMouseHandlers = {
  out: function () {},
  in: function () {}
}

// and using like this
var whatToUse = 'in';
// use
onRegionMouseHandlers[whatToUse]()

Also, you can remove your which choose what function have to be called. You can just add two handlers to two different events.

Sign up to request clarification or add additional context in comments.

Comments

2

You can define the functions as properties of an object, use bracket notation to call the function.

const methods = {
  onRegionMouseOver() {console.log("Over")},
  onRegionMouseOut() {console.log("Out")}
}

let fn = "onRegionMouse";

let type = "Out";

methods[`${fn}${type}`]();

type = "Over";

methods[`${fn}${type}`]();

without template literal or let

var methods = {
  onRegionMouseOver: function onRegionMouseOver() {console.log("Over")},
  onRegionMouseOut: function onRegionMouseOu() {console.log("Out")}
}

var fn = "onRegionMouse";

var type = "Out";

methods[fn + type]();

type = "Over";

methods[fn + type]();

8 Comments

Note that this string definition notation (template literals? don't know how to name this correctly) will work only on a few modern browsers. Or you need transpile this code. Same for let keyword
I think it will be nice if you will mention why you give 2 variants: modern and not-modern.
@SharikovVladislav Not certain if "modern" is the appropriate description of possible variants at Answer, or why two variants are provided at Answer. Rather, 1) access to FOSS browser; 2) consistently updating to newest version of FOSS browser. Where the above might not be possible at 1); or user simply not performing consistent updates at 2).
You really should use just fn+type instead of string interpolation or concat.
@guest271314 No idea. I'd check caniuse and kangax' compat table.
|
0

You can do something like that, provided you declare an object that contains the functions.

var onRegionMouse = {
   Out: onRegionMouseOut,
   Over: onRegionMouseOver
};

Now you can just do

var type = 'Out';
onRegionMouse[type]();

Comments

0

what about:

var myFunctions = {
   out: function onMouseOut()...,
   enter: function onMouseEnter()...
}

You can call it now with myFunctions[ "out" ] ()

2 Comments

There were already 3 similar answers, 2 of them identical to yours.
Oups, when I answered the question has no answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.